home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1999 May: Tool Chest / Developer CD Series Tool Chest (Apple Computer)(May 1999).iso / What's New? / • What was new 03⁄99 / Development Kits / USBDDK_1.2d3 / Examples / PrinterClassDriver / PrinterClassDriver.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-01-18  |  104.7 KB  |  3,111 lines  |  [TEXT/MPS ]

  1. /*
  2.     File:        PrinterClassDriver.c
  3.  
  4.     Contains:    MacOS USB printer class driver
  5.                 [ref. IEEE Std 1284-1994]
  6.  
  7.     Version:    xxx put version here xxx
  8.  
  9.  
  10.  
  11.     Copyright:    1998 by Apple Computer, Inc., all rights reserved.
  12.  
  13. */
  14.  
  15.  
  16. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  17.     includes
  18.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  19. #include <Devices.h>
  20. #include <DriverServices.h>
  21. #include <Interrupts.h>
  22. #include <LowMem.h>
  23. #include <Folders.h>
  24. #include <String.h>
  25. #include <stdio.h>
  26. #include <USB.h>
  27.  
  28. #ifndef __CODEFRAGMENTS__
  29. #include <codefragments.h>
  30. #endif
  31.  
  32. #include "PrinterClassDriver.h"
  33. #include "TradDriverLoaderLib.h"
  34.  
  35. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  36.     constants
  37.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  38. #define MAX_SUFFIX                    127        // maximum copies we'll enter in unit table
  39. #define kUSBParallelDrvrRsrcID    12
  40. #define kMinDrvrUnitNumber            48            // minimum unit table entry which we'll install
  41. #define kUSS720MillisecondDelay    3*1000    // poll every three seconds
  42. #define kUSS720StatusMSDelay        10            // poll one hundred times per second
  43. #define MAX_USB_TRANSFER_SIZE        TRANSFER_SIZE            // zero acts as manifest for conditional compilation
  44.  
  45. #define kUSBAttributeBulk            0x02
  46. #define kUSBInputEndpointMask        0x80
  47.  
  48. enum
  49. {
  50.     kCString = 0,                // StateStr, USBStatusStr selector
  51.     kPString,                    // StateStr, USBStatusStr selector
  52.     kDrvrFirstDigit = 5        // length_byte + ".USB" = 5
  53. };
  54. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  55.     manifest constants
  56. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  57. //
  58. //    DEBUGGING                        extra debugging information to USB Expert Log
  59. //    DOUBLE_BUFFER                    use a page aligned buffer in system heap to double buffer app i/o
  60. //    LOG                                echo all the write data to a log file in the system folder
  61. // LOCK_MEMORY                        LockMemory on the i/o buffer before write and unlock on write completion
  62. // VIRTUAL_MEMORY_CHECK            check the physical addresses of the buffer we pass for write requests
  63. // MACSBUG_ON_READ                break into MacsBug before each read request
  64. //    MACSBUG_ON_READ_COMPLETE    break into MacsBug at each read completion routine
  65. //    MACSBUG_ON_WRITE                break into MacsBug on each write request
  66. // MACSBUG_ON_WRITE_COMPLETE    break into MacsBug at each write completion routine
  67. //
  68. #define DEBUGGING                            0    /* DEBUGGING */
  69. #define DOUBLE_BUFFER                    1    /* DOUBLE_BUFFER */
  70. #define LOG                                    0    /* LOG */
  71. #define LOCK_MEMORY                        1    /* LOCK_MEMORY */
  72. #define MACSBUG_ON_READ                    1    /* MACSBUG_ON_READ */
  73. #define MACSBUG_ON_READ_COMPLETE        0    /* MACSBUG_ON_READ_COMPLETE */ 
  74. #define MACSBUG_ON_WRITE                1    /* MACSBUG_ON_WRITE */
  75. #define MACSBUG_ON_WRITE_COMPLETE    0    /* MACSBUG_ON_WRITE_COMPLETE */ 
  76. #define VIRTUAL_MEMORY_CHECK            0    /* VIRTUAL_MEMORY_CHECK require LOCK_MEMORY, currently broken */
  77.  
  78. #if LOG
  79. #define LOGGING(x)    x
  80. #include <stdio.h>
  81. #else
  82. #define LOGGING(x)
  83. #endif
  84.  
  85. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  86.     globals
  87.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  88. static struct usbPrinterPBStruct    printerClassRecord;
  89. static FSSpec                            printerClassDriverFileSpec;
  90. LOGGING( static FILE                    *logfile );
  91. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  92.     prototypes
  93.   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  94.  
  95. static void    PrinterDeviceCompletionProc(USBPB *pb);
  96. static void SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb );
  97. static void    SoftReset( USBPB *usbprint, short interfaceNum );
  98. static void    CapabilityRequest( USBPB *pb, Ptr p, long length, short config, short interfaceNum, short alternateSetting );
  99. static void    CentronicsStatus( USBPB *usbprint, Ptr p, short interfaceNum );
  100. static void CompletionProc(USBPB *pb);
  101. static int    cstrlen( char *p );
  102. static void    cstrcpy( char *dst, char *src );
  103. static void    cstrcat( char *dst, char *src );
  104.  
  105. void            PrinterDeviceInitiateTransaction(USBPB *pb);
  106.  
  107. OSErr            CFMInitialization( CFragInitBlock *initBlock );
  108.  
  109. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  110.     Name:        HexString8
  111.  
  112.     Input Parameters:    
  113.         v                unsigned long value
  114.         
  115.     Output Parameters:
  116.         p                8 bytes: hex string representing value
  117.         
  118.     Description:
  119.  
  120.     Change History:
  121.         28 Feb 1998,    oja:        Original version.
  122. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  123. static void
  124. HexString8( unsigned long v, unsigned char *p )
  125. {
  126.     int    shift;
  127.     
  128.     for ( shift = 32-4; shift >= 0; shift -= 4 )
  129.     {
  130.         char c = (v >> shift) & 0x0F;
  131.         *p++ = c + (c > 9? ('A'-10): '0');
  132.     }
  133. }
  134.  
  135. #if DEBUG
  136. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  137.     Name:        hexstr
  138.  
  139.     Input Parameters:    
  140.         count                number of bytes
  141.         p                    pointer to bytes
  142.         
  143.     Output Parameters:
  144.         q                    hex dump of data
  145.         
  146.     Description:
  147.  
  148.     Change History:
  149.         28 Jul 1998,    oja:        Original version.
  150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  151. void
  152. hexstr( int count, char *p, char *q );
  153.  
  154. void
  155. hexstr( int count, char *p, char *q )
  156. {
  157.     char *s = p;
  158.     int i = count;
  159.     for ( ; count > 0; --count, ++p )
  160.     {
  161.         int hi, lo;
  162.         hi = (*p >> 4)& 0x0F;
  163.         lo = *p & 0x0F;
  164.         *q++ = '0';
  165.         *q++ = 'x';
  166.         *q++ = hi + (hi > 9? 'A' - 10: '0');
  167.         *q++ = lo + (lo > 9? 'A' - 10: '0');
  168.         *q++ = ' ';
  169.     }
  170.     for ( ; i > 0; --i, ++s )
  171.         *q++ = *s < ' ' || *s > 0x7E? '.': *s;
  172. }
  173. #endif
  174.  
  175. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  176.     Name:        cstrlen
  177.  
  178.     Input Parameters:    
  179.         p            pointer to c-string
  180.         
  181.     Output Parameters:
  182.         int        length of string
  183.  
  184.     Description:
  185.         A replacement for strlen, since we don't want to depend on the
  186.         c library (can cause vm double page faults)
  187.  
  188.     Change History:
  189.         17 Aug 1998,    oja:        Original version.
  190. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  191.  
  192. static int
  193. cstrlen( char *p )
  194. {
  195.     int result = 0;
  196.     
  197.     while ( *p++ != '\0' )
  198.         ++result;
  199.  
  200.     return result;
  201. }
  202.  
  203. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  204.     Name:        cstrcpy
  205.  
  206.     Input Parameters:    
  207.         src        pointer to source c-string
  208.         
  209.     Output Parameters:
  210.         dst        c-string copy of src string
  211.  
  212.     Description:
  213.         A replacement for strcpy, since we don't want to depend on the
  214.         c library (can cause vm double page faults)
  215.  
  216.     Change History:
  217.         17 Aug 1998,    oja:        Original version.
  218. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  219.  
  220. static void
  221. cstrcpy( char *dst, char *src )
  222. {
  223.     while ( (*dst++ = *src++) != 0 )
  224.         ;
  225. }
  226.  
  227. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  228.     Name:        cstrcat
  229.  
  230.     Input Parameters:    
  231.         src        pointer to source c-string
  232.         
  233.     Output Parameters:
  234.         dst        c-string copy of src string
  235.  
  236.     Description:
  237.         A replacement for strcpy, since we don't want to depend on the
  238.         c library (can cause vm double page faults)
  239.  
  240.     Change History:
  241.         17 Aug 1998,    oja:        Original version.
  242. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  243.  
  244. static void
  245. cstrcat( char *dst, char *src )
  246. {
  247.     dst += cstrlen( dst );        // skip to end of the existing string
  248.     while ( (*dst++ = *src++) != 0 )
  249.         ;
  250. }
  251.  
  252. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  253.     Name:        USBStatusStr
  254.  
  255.     Input Parameters:    
  256.         usbStatus            usb error code
  257.         kind                    kPString or kCString
  258.         
  259.     Output Parameters:
  260.         unsigned char *    description of error (c-string or p-string)
  261.  
  262.     Description:
  263.         a simple mapping of errors to human-readable form
  264.  
  265.     Change History:
  266.         24 Apr 1998,    oja:        param to HexString8 was off-by-one
  267.         26 Mar 1998,    oja:        added kStrPrintClass to catenated strings
  268.         28 Feb 1998,    oja:        Original version.
  269. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  270. static unsigned char *
  271. USBStatusStr( OSStatus usbStatus, int kind )
  272. {
  273.     unsigned char *p;
  274.  
  275.     switch ( usbStatus )
  276.     {
  277.         case    kUSBInternalErr:                    p = "\p" kStrPrinterClass "Internal error"; break;
  278.         case    kUSBUnknownDeviceErr:            p = "\p" kStrPrinterClass "Unknown device"; break;
  279.         case    kUSBUnknownPipeErr:                 p = "\p" kStrPrinterClass "Unknown pipe"; break;
  280.         case    kUSBTooManyPipesErr:                p = "\p" kStrPrinterClass "Too many pipes"; break;
  281.         case    kUSBIncorrectTypeErr:            p = "\p" kStrPrinterClass "Incorrect type"; break;
  282.         case    kUSBRqErr:                            p = "\p" kStrPrinterClass "Request error"; break;
  283.         case    kUSBUnknownRequestErr:            p = "\p" kStrPrinterClass "Unknown request"; break;
  284.         case    kUSBTooManyTransactionsErr:    p = "\p" kStrPrinterClass "Too many transactions"; break;
  285.         case    kUSBAlreadyOpenErr:                p = "\p" kStrPrinterClass "Already open"; break;
  286.         case    kUSBNoDeviceErr:                    p = "\p" kStrPrinterClass "No device"; break;
  287.         case    kUSBDeviceErr:                        p = "\p" kStrPrinterClass "Device error"; break;
  288.         case    kUSBOutOfMemoryErr:                p = "\p" kStrPrinterClass "Out of memory"; break;
  289.         case    kUSBNotFound:                        p = "\p" kStrPrinterClass "Not found"; break;
  290.         case    kUSBLinkErr:                        p = "\p" kStrPrinterClass "Link Err"; break;
  291.         case    kUSBCRCErr:                            p = "\p" kStrPrinterClass "Comms/Device err, bad CRC";  break;        
  292.         case    kUSBBitstufErr:                    p = "\p" kStrPrinterClass "Comms/Device err, bitstuffing"; break;        
  293.         case    kUSBDataToggleErr:                p = "\p" kStrPrinterClass "Comms/Device err, Bad data toggle"; break;        
  294.         case    kUSBEndpointStallErr:            p = "\p" kStrPrinterClass "Device didn't understand"; break;        
  295.         case    kUSBNotRespondingErr:            p = "\p" kStrPrinterClass "No device, device hung"; break;        
  296.         case    kUSBPIDCheckErr:                    p = "\p" kStrPrinterClass "Comms/Device err, PID CRC error"; break;        
  297.         case    kUSBWrongPIDErr:                    p = "\p" kStrPrinterClass "Comms/Device err, Bad or wrong PID"; break;        
  298.         case    kUSBOverRunErr:                    p = "\p" kStrPrinterClass "Packet too large or more data than buffer"; break;        
  299.         case    kUSBUnderRunErr:                    p = "\p" kStrPrinterClass "Less data than buffer"; break;        
  300.         case    kUSBRes1Err:                        p = "\p" kStrPrinterClass "kUSBRes1Err"; break;        
  301.         case    kUSBRes2Err:                        p = "\p" kStrPrinterClass "kUSBRes1Err"; break;        
  302.         case    kUSBBufOvrRunErr:                    p = "\p" kStrPrinterClass "Buffer over run error"; break;        
  303.         case    kUSBBufUnderRunErr:                p = "\p" kStrPrinterClass "Buffer under run error"; break;        
  304.         case    kUSBNotSent1Err:                    p = "\p" kStrPrinterClass "Transaction not sent1"; break;        
  305.         case    kUSBNotSent2Err:                    p = "\p" kStrPrinterClass "Transaction not sent2"; break;    
  306.         default:
  307.             p = "\p" kStrPrinterClass "Unknown error nnnnnnnn";
  308.             HexString8( usbStatus, p + *p - 8 + 1 );
  309.             break;
  310.     }
  311.     
  312.     return kind == kPString? p: p + 1;
  313. }
  314.  
  315. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  316.     Name:        StateStr
  317.  
  318.     Input Parameters:    
  319.         usbRefCon            usb error code
  320.         kind                    kPString or kCString
  321.         
  322.     Output Parameters:
  323.         unsigned char *    description of state (c-string or p-string)
  324.  
  325.     Description:
  326.         a simple mapping of states to human-readable form
  327.  
  328.     Change History:
  329.         24 Apr 1998,    oja:        param to HexString8 was off-by-one
  330.         26 Mar 1998,    oja:        added kStrPrintClass to catenated strings
  331.         28 Feb 1998,    oja:        Original version.
  332. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  333. static unsigned char *
  334. StateStr( OSStatus refCon, int kind )
  335. {
  336.     unsigned char *p;
  337.  
  338.     refCon &= ~(kTransactionPending | kRetryTransaction | kReturnFromDriver);
  339.     switch ( refCon )
  340.     {
  341.         case kGetCapabilityString:                    p = "\p" kStrPrinterClass "kGetCapabilityString"; break;
  342.         case kDelayGetCapability:                    p = "\p" kStrPrinterClass "kDelayGetCapability"; break;
  343.         case kFindBulkOutPipe:                        p = "\p" kStrPrinterClass "kFindBulkOutPipe"; break;
  344.         case kFindBulkInPipe:                        p = "\p" kStrPrinterClass "kFindBulkInPipe"; break;
  345.         case kTaskTimeRequired:                        p = "\p" kStrPrinterClass "kTaskTimeRequired"; break;
  346.         default:
  347.             p = "\p" kStrPrinterClass "Unknown state nnnnnnnn";
  348.             HexString8( refCon, p + *p - 8 + 1 );
  349.             break;
  350.     }
  351.     return kind == kPString? p: p + 1;    
  352. }
  353.  
  354. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  355.     Name:        HiHex
  356.  
  357.     Input Parameters:    
  358.         v                        only low byte used
  359.         
  360.     Output Parameters:
  361.         <function result>    high nibble represented as ASCII char
  362.         
  363.     Description:
  364.  
  365.     Change History:
  366.         20 Mar 1998,    oja:        Original version.
  367. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  368. static unsigned char
  369. HiHex( int v )
  370. {
  371.     unsigned char    hinibble = (v >> 4) & 0x0f;
  372.     return hinibble + ((hinibble > 9)? ('A'-10): '0');
  373. }
  374.  
  375. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  376.     Name:        LoHex
  377.  
  378.     Input Parameters:    
  379.         v                        only low byte used
  380.         
  381.     Output Parameters:
  382.         <function result>    low nibble represented as ASCII char
  383.         
  384.     Description:
  385.  
  386.     Change History:
  387.         20 Mar 1998,    oja:        Original version.
  388. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  389. static unsigned char
  390. LoHex( int v )
  391. {
  392.     unsigned char    lonibble = v & 0x0f;
  393.     return lonibble + ((lonibble > 9)? ('A'-10): '0');
  394. }
  395.  
  396. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  397.     Name:        immediateError
  398.  
  399.     Input Parameters:    
  400.         
  401.     Output Parameters:
  402.         
  403.     Description:
  404.  
  405.     Change History:
  406.         28 Feb 1998,    oja:        Original version.
  407. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  408. static Boolean
  409. immediateError(OSStatus err)
  410. {
  411.     return((err != kUSBPending) && (err != noErr) );
  412. }
  413.  
  414. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  415.     Name:        SetNullUSBParamBlock
  416.  
  417.     Input Parameters:    
  418.         pb                    pointer to USB parameter block
  419.         dev                USB device reference
  420.     Output Parameters:
  421.         pb                    all fields set to default values
  422.  
  423.     Description:
  424.         setup a USB parameter block for use by the current device
  425.  
  426.     Change History:
  427.          8 Jun 1998,    oja:        modified for new param blocks
  428.         28 Feb 1998,    oja:        Original version.
  429. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  430. static void
  431. SetNullUSBParamBlock( USBDeviceRef dev, USBPB *pb )
  432. {
  433.     pb->qlink = NULL;
  434.     pb->qType = 0;
  435.     pb->pbLength = sizeof(USBPB);
  436.     pb->pbVersion = kUSBCurrentPBVersion;
  437.     pb->usbFlags = 0;
  438.     pb->usbStatus = noErr;
  439.     pb->usbCompletion = (USBCompletion) NULL;
  440.  
  441.     pb->usbReference = dev;
  442. }
  443.  
  444.  
  445. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  446.     Name:        ParseCapability
  447.  
  448.     Input Parameters:    
  449.         capability            pointer to 1284-1994 capability string
  450.         attribute            pointer to c-string key we're retrieving (terminate with colon)
  451.         *result_length        maximum length of the result 
  452.         
  453.     Output Parameters:
  454.         result                c-string which followed the key and was terminated by semi-colon
  455.                                 (semi-colon has been stripped)
  456.         *result_length        actual length of the result (may be zero)
  457.     
  458.     Description:
  459.         Search for "attribute" in the 1284 "capability" string
  460.         The identifier is terminated with a semi-colon
  461.  
  462.         Return the attribute in result
  463.             null-string if attribute not found.
  464.  
  465.     Change History:
  466.         20 Jul 1998,    oja:        fix computation of target_length
  467.         28 Feb 1998,    oja:        Original version.
  468. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  469. static void
  470. ParseCapability(
  471.     unsigned char    *capability,
  472.     unsigned char    *attribute,
  473.     unsigned char    *result,
  474.     int                *result_length 
  475. )
  476. {
  477.     //
  478.     //    search for "attribute" in the 1284 "capability" string
  479.     //
  480.     //    the identifier is terminated with a semi-colon
  481.     //
  482.     //    return the attribute in result
  483.     //            null-string if attribute not found
  484.     //
  485.     //    <to do> skip blanks, isolate colon, skip blanks
  486.     //
  487.     int                source_length,
  488.                         target_length;
  489.     unsigned char    *source,
  490.                         *target,
  491.                         *destination;
  492.     //
  493.     //    begin a brute force search
  494.     //
  495.     source = attribute;
  496.     source_length = cstrlen((char *)attribute );
  497.  
  498.     target = capability + 2;    // skip the length
  499.     target_length =  capability[1] | (capability[0] << 8);
  500.     target_length -= 2;            // don't count the length
  501.     while ( target_length >= source_length )
  502.     {
  503.         if ( memcmp( source, target, source_length ) == 0 )
  504.             break;
  505.         --target_length;
  506.         ++target;
  507.     }
  508.  
  509.     destination = result;
  510.     *destination = 0;    // empty result
  511.  
  512.     target += source_length;
  513.     target_length -= source_length;    // skip the attribute string
  514.  
  515.     if ( target_length > 0 )
  516.     {
  517.         //
  518.         //    we found the attribute in the capability string
  519.         //
  520.         while ( destination - result < *result_length )    // arbitrarily limit reply
  521.         {
  522.             if ( *target == ';' )
  523.                 break;
  524.             *destination++ = *target++;        // copy a byte of attribute over
  525.         }
  526.         *destination++ = '\0';                        // trailing NUL
  527.         *result_length = destination - result;    // report the length of the data (with trailing NUL)
  528.     }
  529. }
  530.  
  531.  
  532. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  533.     Name:        GetClass
  534.  
  535.     Input Parameters:    
  536.         capability            pointer to 1284-1994 capability string
  537.         *result_length        maximum length of the result 
  538.         
  539.     Output Parameters:
  540.         result                c-string extracted from the MODEL key
  541.         *result_length        actual length of the result  (may be zero)
  542.         
  543.     Description:
  544.         CLASS is a Microsoft extension to the 1284-capability string
  545.         if we don't find it
  546.             we assume that the device is a printer
  547.         Since the USB hardware has already indicated this, we're really allowing
  548.         devices which aren't printers to be reached via the DRVRs we've installed.
  549.  
  550.     Change History:
  551.         26 Mar 1998,    oja:        result_length is output too
  552.         28 Feb 1998,    oja:        Original version.
  553. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  554. static void
  555. GetClass(
  556.     unsigned char    *capability,
  557.     unsigned char    *result,
  558.     int                *result_length
  559. )
  560. {
  561.     //
  562.     //    We supply the upper-case PRINTER to be consistent with 1284-1994
  563.     //        if we don't find a class.
  564.     //
  565.     ParseCapability( capability, (unsigned char *) "CLASS:", result, result_length);
  566.     if ( *result == '\0' )
  567.         ParseCapability( capability, (unsigned char *) "CLS:", result, result_length);
  568.     if ( *result == '\0' )
  569.         cstrcpy( (char *)result, "PRINTER" );
  570. }
  571.  
  572.  
  573. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  574.     Name:        GetModel
  575.  
  576.     Input Parameters:    
  577.         capability            pointer to 1284-1994 capability string
  578.         *result_length        maximum length of the result 
  579.         
  580.     Output Parameters:
  581.         result                c-string extracted from the MODEL key
  582.         *result_length        actual length of the result  (may be zero)
  583.             
  584.     Description:
  585.         MODEL is a required field of the 1284-capability string
  586.         MODEL may be abbreviated MDL
  587.  
  588.     Change History:
  589.         26 Mar 1998,    oja:        result_length is output too
  590.         28 Feb 1998,    oja:        Original version.
  591. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  592. static void
  593. GetModel(
  594.     unsigned char    *capability, 
  595.     unsigned char    *result,
  596.     int                *result_length
  597. )
  598. {
  599.     //
  600.     //    Most manufacturers abbreviate, so we search for MDL first
  601.     //
  602.     ParseCapability( capability, (unsigned char *) "MDL:", result, result_length );
  603.     if ( *result == '\0' )
  604.         ParseCapability( capability, (unsigned char *) "MODEL:", result, result_length );
  605. }
  606.  
  607.  
  608. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  609.     Name:        GetCommandSet
  610.  
  611.     Input Parameters:    
  612.         
  613.     Output Parameters:
  614.         
  615.     Description:
  616.  
  617.     Change History:
  618.         11 Nov 1998,    oja:        look for COMMAND SET not COMMAND-SET
  619.         28 Feb 1998,    oja:        Original version.
  620. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  621. static void
  622. GetCommandSet(
  623.     unsigned char *capability, 
  624.     unsigned char *result,
  625.     int *result_length
  626. )
  627. {
  628.     //
  629.     //    COMMAND-SET is a required field of the 1284-capability string
  630.     //    COMMAND-SET may be abbreviated CMD
  631.     //
  632.     ParseCapability( capability, (unsigned char *) "CMD:", result, result_length );
  633.     if ( *result == '\0' )
  634.         ParseCapability( capability, (unsigned char *) "COMMAND SET:", result, result_length );
  635. }
  636.  
  637. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  638.     Name:        GetManufacturer
  639.  
  640.     Input Parameters:    
  641.         
  642.     Output Parameters:
  643.         
  644.     Description:
  645.  
  646.     Change History:
  647.         26 Jun 1998,    oja:        Original version.
  648. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  649. static void
  650. GetManufacturer(
  651.     unsigned char *capability, 
  652.     unsigned char *result,
  653.     int *result_length
  654. )
  655. {
  656.     //
  657.     //    MANUFACTURER is a required field of the 1284-capability string
  658.     //    MANUFACTURER may be abbreviated MFG
  659.     //
  660.     ParseCapability( capability, (unsigned char *) "MFG:", result, result_length );
  661.     if ( *result == '\0' )
  662.         ParseCapability( capability, (unsigned char *) "MANUFACTURER:", result, result_length );
  663. }
  664.  
  665.  
  666. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  667.     Name:        DeregisterDevice
  668.  
  669.     Input Parameters:    
  670.         pPrinterPB
  671.  
  672.     Output Parameters:
  673.         <none>
  674.         
  675.     Description:
  676.         remove the device from the name registry
  677.  
  678.     Change History:
  679.         11 Jun 1998,    oja:        test from RegistryCStrEntryLookup was wrong direction
  680.         17 Apr 1998,    oja:        Original version.
  681. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  682. static OSStatus
  683. DeregisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  684. {
  685.     OSStatus        err;
  686.     RegEntryID    self;
  687.  
  688.     RegistryEntryIDInit( &self );
  689.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  690.     if ( err == noErr )
  691.     {
  692.         err = RegistryEntryDelete( &self);
  693.     }
  694.     RegistryEntryIDDispose(&self);
  695.     if (err == noErr &&  pPrinterPB->outRefNum != -1 )
  696.         err = TradRemoveDriver( pPrinterPB->outRefNum, false );
  697.     if (err == noErr &&  pPrinterPB->inRefNum != -1 )
  698.         err = TradRemoveDriver( pPrinterPB->inRefNum, false );
  699.     
  700.     return err;
  701. }
  702.  
  703. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  704.     Name:        RegisterDevice
  705.  
  706.     Input Parameters:    
  707.         pPrinterPB
  708.  
  709.     Output Parameters:
  710.         <none>
  711.         
  712.     Description:
  713.         add the device into the name registry; we can't insert just the node
  714.         if the parent nodes aren't present.
  715.  
  716.         if it isn't present
  717.             insert the device CLASS into the registry
  718.         if it isn't present
  719.             insert the device MODEL into the registry
  720.         finally insert the device itself into the registry
  721.             we're careful to rename multiple devices
  722.  
  723.     Change History:
  724.         16 Nov 1998,    oja:        better support for attributes which aren't in string
  725.         16 Jul 1998,    oja:        fix params to sprintf
  726.          8 Jun 1998,    oja:        don't use register param (CW build)
  727.         26 Mar 1998,    oja:        only register significant part of drvrNames 
  728.                                         log null model name to Expert
  729.                                         register command set 
  730.         28 Feb 1998,    oja:        Original version.
  731. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  732. static OSStatus
  733. RegisterDevice( struct usbPrinterPBStruct *pPrinterPB )
  734. {
  735.     //
  736.     //    add the device into the name registry
  737.     //    if it isn't present
  738.     //        insert the device CLASS into the registry
  739.     //    if it isn't present
  740.     //        insert the device MODEL into the registry
  741.     //    finally insert the device itself into the registry
  742.     //        we're careful to rename multiple devices
  743.     //
  744.     Str255        identification,
  745.                     devclass,
  746.                     model,
  747.                     commands,
  748.                     tempstr;
  749.     RegEntryID    parent, where, self;
  750.     OSStatus        err;
  751.     int            model_length,
  752.                     command_length,
  753.                     class_length;
  754.  
  755.     class_length = sizeof(devclass);
  756.     GetClass( pPrinterPB->pCapabilityString, devclass, &class_length );
  757.  
  758.     command_length = sizeof(commands);
  759.     GetCommandSet(pPrinterPB->pCapabilityString, commands, &command_length );
  760.  
  761.     cstrcpy( (char *)pPrinterPB->name, (char *)"Devices:device-tree:" );
  762.     cstrcat( (char *)pPrinterPB->name, (char *)devclass );
  763.     
  764.     RegistryEntryIDInit( &where );
  765.     err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name, &where );
  766.     if ( err == nrPathNotFound ) 
  767.     {
  768.         //    class not in registry
  769.         //        create a node for all devices of this CLASS
  770.         //
  771.         RegistryEntryIDInit( &parent );
  772.         err = RegistryCStrEntryLookup( nil, "Devices:device-tree:" , &parent );
  773.         if ( err == noErr )
  774.             err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &where );
  775.         RegistryEntryIDDispose(&parent);
  776.  
  777.     }
  778.     //
  779.     //    add this model into the name registry of this class
  780.     //
  781.     if ( err == noErr )
  782.     {
  783.         model_length = sizeof(model);
  784.         GetModel( pPrinterPB->pCapabilityString, model, &model_length );
  785.         if ( *model != '\0' )
  786.         {
  787.             cstrcpy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  788.             cstrcat( (char *)pPrinterPB->name, (char *)devclass );
  789.             cstrcat( (char *)pPrinterPB->name, ":" );
  790.             cstrcat( (char *)pPrinterPB->name, (char *)model );
  791.             RegistryEntryIDInit( &self );
  792.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  793.             if ( err != noErr )
  794.             {
  795.                 // model not in registry
  796.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  797.             }
  798.             RegistryEntryIDDispose(&self);
  799.         }
  800.     }
  801.     //
  802.     //    add this instance of this model of this class
  803.     //        into the name registry
  804.     //
  805.     if ( *model == '\0'  )
  806.     {
  807.         //
  808.         //    possibly the cable isn't firmly connected or the printer isn't switched on
  809.         //
  810.         err = kUSBInternalErr;
  811.         USBExpertFatalError(pPrinterPB->deviceRef, err, "\p"kStrPrinterClass "\pModel undefined", 0);
  812.     }
  813.     if ( err == noErr )
  814.     {
  815.         //
  816.         //    start off by identifying the device simply by the model name
  817.         //        increment the numeric suffix until we successfully registry the device
  818.         //
  819.         Str32    suffix;
  820.         int    numeric_suffix;
  821.  
  822.         cstrcpy( (char *)identification, (char *)model );
  823.         RegistryEntryIDInit( &self );
  824.         for ( numeric_suffix = 1; numeric_suffix < MAX_SUFFIX; ++numeric_suffix )
  825.         {
  826.             cstrcpy( (char *)pPrinterPB->name, "Devices:device-tree:" );
  827.             cstrcat( (char *)pPrinterPB->name, (char *)devclass );
  828.             cstrcat( (char *)pPrinterPB->name, ":" );
  829.             cstrcat( (char *)pPrinterPB->name, (char *)model );
  830.             cstrcat( (char *)pPrinterPB->name, ":" );
  831.             cstrcat( (char *)pPrinterPB->name, (char *)identification );
  832.             err = RegistryCStrEntryLookup( nil, (char const *) pPrinterPB->name , &self );
  833.             if ( err != noErr )
  834.             {
  835.                 // enter device in registry
  836.                 err = RegistryCStrEntryCreate( nil, (char const *) pPrinterPB->name, &self );
  837.                 if ( err == noErr )
  838.                     err = RegistryPropertyCreate( &self, "drvrOut", &pPrinterPB->driverOutName, 1 + pPrinterPB->driverOutName[0] );
  839.                 if ( err == noErr )
  840.                     err = RegistryPropertyCreate( &self, "outRef", &pPrinterPB->outRefNum, sizeof(pPrinterPB->outRefNum) );
  841.                 if ( err == noErr )
  842.                     err = RegistryPropertyCreate( &self, "drvrIn", &pPrinterPB->driverInName, 1 + pPrinterPB->driverInName[0] );
  843.                 if ( err == noErr )
  844.                     err = RegistryPropertyCreate( &self, "inRef", &pPrinterPB->inRefNum, sizeof(pPrinterPB->inRefNum) );
  845.                 if ( err == noErr )
  846.                     err = RegistryPropertyCreate( &self, "privateData", &pPrinterPB, sizeof(pPrinterPB) );
  847.                 if ( err == noErr )
  848.                     err = RegistryPropertyCreate( &self, "read", &pPrinterPB->r, sizeof(QueueUSBReadUPP) );
  849.                 if ( err == noErr )
  850.                     err = RegistryPropertyCreate( &self, "write", &pPrinterPB->w, sizeof(QueueUSBWriteUPP) );
  851.                 if ( err == noErr && *commands != '\0' )
  852.                     err = RegistryPropertyCreate( &self, "command-set", &commands, command_length );
  853.                 break;
  854.             }
  855.             //
  856.             //    if this name didn't succeed
  857.             //        try the next numeric suffix
  858.             //
  859.             sprintf( (char *)suffix, " %d", numeric_suffix );
  860.             cstrcpy( (char *)identification, (char *)model );
  861.             cstrcat( (char *)identification, (char *)suffix );
  862.         }
  863.         RegistryEntryIDDispose(&self);
  864.     }
  865.     
  866.     CStrToPStr((unsigned char *)tempstr, (char const *)pPrinterPB->name );
  867.     
  868.     USBExpertStatus( pPrinterPB->deviceRef, tempstr, err );
  869.     RegistryEntryIDDispose(&where);
  870.  
  871.     LOGGING( logfile = fopen( "USBPrinter.log", "wb+" ) );
  872.     return err;
  873. }
  874.  
  875. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  876.     Name:        LoadResources
  877.  
  878.     Input Parameters:
  879.         pPrinterPB            pointer to class driver's private storage
  880.         
  881.     Output Parameters:
  882.         OSStatus                resource load error
  883.         
  884.     Description:
  885.         Initialize time is the only safe time to to load resources from our file.
  886.         Here's where we load resources and detach them from the resource manager.
  887.         Later we'll use these private copies instead of GetResource calls.
  888.         
  889.         Using the file spec that we got from the CFMInitialization routine, open
  890.         our resource fork.
  891.  
  892.     Change History:
  893.         11 Jun 1998,    oja:        removed hardcoded filename, use printerClassDriverFileSpec
  894.         20 Mar 1998,    oja:        Original version.
  895. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  896. static OSStatus
  897. LoadResources( struct usbPrinterPBStruct *pPrinterPB )
  898. {
  899.     short            rf = -1;                // class driver resource fork
  900.     OSStatus        err;
  901.  
  902.     //
  903.     //    open the resource fork of this class driver
  904.     //
  905.     rf = FSpOpenResFile( &printerClassDriverFileSpec,fsRdPerm );
  906.     err = ResError();
  907.     
  908.     //
  909.     //    load the DRVR that we'll stick in the unit table
  910.     //
  911.     pPrinterPB->hDrvr = NULL;
  912.     if ( err == noErr )
  913.     {
  914.         pPrinterPB->hDrvr = (DRVRHeaderHandle) Get1Resource( 'DRVR',  kUSBParallelDrvrRsrcID );
  915.         if ( pPrinterPB->hDrvr != NULL )
  916.             DetachResource( (Handle) pPrinterPB->hDrvr );
  917.         err = ResError();
  918.     }
  919.     
  920.     if ( rf != -1 )
  921.         CloseResFile( rf );
  922.     
  923.     return err;
  924. }
  925.  
  926. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  927.     Name:        InstallDrivers
  928.  
  929.     Input Parameters:
  930.         pPrinterPB
  931.         
  932.     Output Parameters:
  933.         OSStatus            error code
  934.         
  935.     Description:
  936.         install read and write drivers in the unit table
  937.             we have separate drivers so that we can support a full-duplex protocol
  938.         rename the driver we just installed (so multiple copies don't conflict)
  939.         We use the DRVR -refnum-1 so that the driver name has the same hex chars
  940.             as the driver number (for manual verification in MacsBug)
  941.  
  942.     Change History:
  943.         13 Jul 1998,    oja:        init err to noErr
  944.         26 Mar 1998,    oja:        Use refnum -1, use infix location to enumerate
  945.                                         DRVR
  946.         28 Feb 1998,    oja:        Original version.
  947. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  948. static OSStatus
  949. InstallDrivers( struct usbPrinterPBStruct *pPrinterPB )
  950. {
  951.     //
  952.     //    install the driver in the unit table
  953.     //    rename the driver we just installed (so multiple copies don't conflict)
  954.     //    
  955.     short            refNum;                // DRVR refNum
  956.     OSStatus        err =  paramErr;    // couldn't find driver
  957.  
  958.     if ( pPrinterPB->hDrvr != NULL )
  959.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->outRefNum );
  960.  
  961.     if ( err == noErr )
  962.     {
  963.         UnitNumber        unit;
  964.         DriverFlags        flags;
  965.         DRVRHeaderPtr    hdr;
  966.         unsigned char    *suffix,        // append "In" and "Out"
  967.                             *infix;        // driver reference number follows the ".USB"
  968.  
  969.         TradGetDriverInformation( pPrinterPB->outRefNum, &unit, &flags, pPrinterPB->driverOutName, &hdr );
  970.         BlockMove( pPrinterPB->driverOutName, pPrinterPB->driverInName, 1 + pPrinterPB->driverOutName[0] );
  971.         
  972.         suffix = pPrinterPB->driverOutName + pPrinterPB->driverOutName[0] - 2;
  973.         infix = pPrinterPB->driverOutName + kDrvrFirstDigit;
  974.         infix[0] = HiHex( -pPrinterPB->outRefNum -1 );
  975.         infix[1] = LoHex( -pPrinterPB->outRefNum -1 );
  976.         suffix[0] = 'O';
  977.         suffix[1] = 'u';
  978.         suffix[2] = 't';
  979.         TradRenameDriver( pPrinterPB->outRefNum, pPrinterPB->driverOutName );
  980.         //
  981.         //    set the driver data to point to our parameter block
  982.         //
  983.         err = OpenDriver( pPrinterPB->driverOutName, &refNum );
  984.         if ( err == noErr )
  985.         {
  986.             struct usbPrinterPBStruct *param = pPrinterPB;
  987.             err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  988.             CloseDriver( refNum );
  989.         }
  990.         err = TradInstallDriverFromHandle( pPrinterPB->hDrvr, kMinDrvrUnitNumber, TradHighestUnitNumber() + 1, &pPrinterPB->inRefNum );
  991.         if ( err == noErr )
  992.         {
  993.             
  994.             suffix = pPrinterPB->driverInName + pPrinterPB->driverInName[0] - 1;
  995.             infix = pPrinterPB->driverInName + kDrvrFirstDigit;
  996.             infix[0] = HiHex( -pPrinterPB->inRefNum -1 );
  997.             infix[1] = LoHex( -pPrinterPB->inRefNum -1 );
  998.             suffix[0] = 'I';
  999.             suffix[1] = 'n';
  1000.             TradRenameDriver( pPrinterPB->inRefNum, pPrinterPB->driverInName );
  1001.             //
  1002.             //    set the driver data to point to our parameter block
  1003.             //
  1004.             err = OpenDriver( pPrinterPB->driverInName, &refNum );
  1005.             if ( err == noErr )
  1006.             {
  1007.                 struct usbPrinterPBStruct *param = pPrinterPB;
  1008.                 err = Control( refNum, kDrvrPrivateSetStorage, ¶m );
  1009.                 CloseDriver( refNum );
  1010.             }
  1011.         }
  1012.     }
  1013.  
  1014.     return err;
  1015. }
  1016.  
  1017. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1018.     Name:        GetCapability
  1019.  
  1020.     Input Parameters:    
  1021.         
  1022.     Output Parameters:
  1023.         
  1024.     Description:
  1025.         Asynchronous completion.
  1026.  
  1027.     Change History:
  1028.         28 Feb 1998,    oja:        Original version.
  1029. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1030. static void
  1031. GetCapability( struct usbPrinterPBStruct *pPrinterPB, unsigned char *p, int length )
  1032. {
  1033.     //
  1034.     //    queue a transaction to retrieve the 1284 capability string
  1035.     //        we must have assigned the interface by this point since the capability string
  1036.     //        may vary with the interface
  1037.     //
  1038.     OSStatus        err;
  1039.     USBPB            *pb = &pPrinterPB->pb;
  1040.     
  1041.     SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  1042.     
  1043.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1044.     pb->usbBuffer = 0;
  1045.     pb->usbActCount = 0;
  1046.     pb->usbReqCount = 0;
  1047.  
  1048.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1049.     pb->usb.cntl.WValue = pPrinterPB->configurationNumber;            // configuration
  1050.     pb->usb.cntl.WIndex = (pPrinterPB->interfaceNumber<<8) | pPrinterPB->alternateSetting;
  1051.  
  1052.     pb->usbReqCount = length;
  1053.     pb->usbBuffer = p;
  1054.  
  1055.     pb->usbRefcon |= kTransactionPending;
  1056.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1057.     err = USBDeviceRequest(pb);
  1058.     if(immediateError(err))
  1059.     {
  1060.         USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "GetCapability", 0);
  1061.         pb->usbRefcon |= kReturnFromDriver;
  1062.     }
  1063. }
  1064.  
  1065. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1066.     Name:        IsLucentCable
  1067.  
  1068.     Input Parameters:    
  1069.         dev            USB device descriptor
  1070.         
  1071.     Output Parameters:
  1072.         Return 1 if the USB device is a USB-parallel cable
  1073.         
  1074.     Description:
  1075.         
  1076.  
  1077.     Change History:
  1078.         28 Feb 1998,    oja:        Original version.
  1079. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1080. static int
  1081. IsLucentCable( USBDeviceDescriptor    *dev )
  1082. {
  1083.     return ( USBToHostWord(dev->vendor) == 0x47E && USBToHostWord(dev->product) == 0x1001 )? 1: 0;
  1084. }
  1085.  
  1086.  
  1087. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1088.     Name:        GetInterface
  1089.  
  1090.     Input Parameters:    
  1091.         
  1092.     Output Parameters:
  1093.         
  1094.     Description:
  1095.         Asynchronous completion.
  1096.  
  1097.     Change History:
  1098.         28 Feb 1998,    oja:        Original version.
  1099. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1100. static void
  1101. GetInterface( USBPB *pb, UInt8 *alt )
  1102. {
  1103.     //
  1104.     //    make sure we account for any alternate interface currently in use by the device
  1105.     //
  1106.     OSStatus    err;
  1107.  
  1108.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBStandard, kUSBInterface);
  1109.  
  1110.     pb->usb.cntl.BRequest = kUSBRqGetInterface;
  1111.     pb->usb.cntl.WValue = 0; 
  1112.     pb->usb.cntl.WIndex = 0;
  1113.  
  1114.     pb->usbReqCount = sizeof(UInt8);        // single byte is requested
  1115.     pb->usbBuffer = alt;
  1116.  
  1117.     pb->usbStatus = 0;
  1118.     pb->usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  1119.     pb->usbRefcon |= kTransactionPending;
  1120.  
  1121.     err = USBDeviceRequest(pb);
  1122.     if(immediateError(err))
  1123.     {
  1124.         USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "GetInterface", 0);
  1125.         pb->usbRefcon |= kReturnFromDriver;
  1126.     }
  1127. }
  1128.  
  1129.  
  1130. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1131.     Name:        ReadCompletion
  1132.  
  1133.     Input Parameters:    
  1134.         pb                        USB parameter block
  1135.         
  1136.     Output Parameters:
  1137.         <none>
  1138.  
  1139.     Description:
  1140.         USB read requests complete here.
  1141.         We dequeue the MacOS DRVR read requests
  1142.  
  1143.     Change History:
  1144.         10 Aug 1998,    oja:        set readDrvr.ctl to NULL when finished
  1145.         28 Jul 1998,    oja:        breakdown transactions into MAX_USB_TRANSFER_SIZE
  1146.         27 Jul 1998,    oja:        lock memory (UIM doesn't do this properly)
  1147.         20 Jul 1998,    oja:        retry transactions
  1148.          8 Jun 1998,    oja:        clear stalls on error
  1149.         28 Feb 1998,    oja:        Original version.
  1150. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1151. static void
  1152. ReadCompletion(USBPB *pb)
  1153. {
  1154.     //    call the user completion routine
  1155.     struct usbPrinterPBStruct
  1156.             *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1157.     IOParamPtr     clientParam = pPrinterPB->readDrvr.pb;
  1158.     OSStatus        err = pb->usbStatus;
  1159.     DCtlPtr            ctlLocal;
  1160.  
  1161. #if MACSBUG_ON_READ_COMPLETE
  1162.     Str255    text;
  1163.     sprintf( (char *)text, " PrinterClass Read Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1164.     text[0] = cstrlen((char *)text); // c2pstr
  1165.     DebugStr( text );
  1166. #endif
  1167.  
  1168. #if DOUBLE_BUFFER
  1169.     //
  1170.     //    copy the user data from our page aligned buffer
  1171.     //
  1172.     USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "ReadCompletion - read  " , (UInt32)pb->usbActCount );
  1173.  
  1174.     if ( pb->usbActCount > 0 )
  1175.         BlockCopy( pPrinterPB->pageReadAlignedBuffer, clientParam->ioBuffer + clientParam->ioActCount, pb->usbActCount );
  1176. #endif
  1177.     //    update the amount of data actually transferred
  1178.     clientParam->ioActCount += pb->usbActCount;
  1179.  
  1180.     switch( pb->usbStatus )
  1181.     {
  1182.         //
  1183.         //    only retry low level hardware problems
  1184.         //        note: abort transactions will end up here as well
  1185.         //
  1186.     case kUSBLinkErr:
  1187.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1188.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1189.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1190.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1191.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1192.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1193.         if (  --(pPrinterPB->readRetryCount) > 0 ) 
  1194.         {
  1195.             // we got an error, and we still want to retry, clear any stalls
  1196.             USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "ReadCompletion retry" , pb->usbStatus );
  1197.             USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1198.             pb->usbStatus = noErr;
  1199.         }
  1200.         break;
  1201.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1202.         USBClearPipeStallByReference(pPrinterPB->readPipeRef);
  1203.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1204.         break;
  1205.         //
  1206.         //    any other error will be reported to the client
  1207.         //
  1208.     default:
  1209.     case noErr:
  1210.         break;
  1211.     }
  1212.     if ( pb->usbStatus == noErr &&                                     // there were no problems
  1213.         pb->usbActCount >= pb->usbReqCount &&                        // we got all the data we requested
  1214.         clientParam->ioActCount < clientParam->ioReqCount )    // we still want more data
  1215.     {
  1216.         //
  1217.         //    haven't finish the client's request
  1218.         //        update the pointers and start another bulk read transaction
  1219.         //
  1220. #if LOCK_MEMORY
  1221.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1222.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass ReadCompletion UnlockMem failed" ) );
  1223. #endif
  1224.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1225.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1226. #if MAX_USB_TRANSFER_SIZE
  1227.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1228.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1229. #endif
  1230. #if DOUBLE_BUFFER
  1231.         //
  1232.         //    make sure we have enough room in our buffer
  1233.         //
  1234.         if ( pb->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1235.             pb->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1236.         pb->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1237. #endif
  1238. #if LOCK_MEMORY
  1239.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1240.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass ReadCompletion LockMem failed" ) );
  1241.         if ( err == noErr )
  1242. #endif
  1243.             err = USBBulkRead( pb );
  1244.         if ( immediateError(err) )
  1245.         {
  1246.             USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "ReadCompletion finish immed err" , err );
  1247.  
  1248.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1249.             if ( pPrinterPB->readDrvr.ctl != NULL )
  1250.             {
  1251.                 ctlLocal = pPrinterPB->readDrvr.ctl;
  1252.                 pPrinterPB->readDrvr.ctl = NULL;
  1253.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1254.             }
  1255.         }
  1256.     }
  1257.     else
  1258.     {
  1259.         //
  1260.         //        either we have an error which we're not retrying
  1261.         //            or we successfully completed
  1262.         //
  1263. #if LOCK_MEMORY
  1264.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1265.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass ReadCompletion concluded UnlockMem failed" ) );
  1266. #endif
  1267.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "ReadCompletion Error" , pb->usbStatus ) );
  1268.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1269.         USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "readDrvr.ctl = " , (UInt32)pPrinterPB->readDrvr.ctl );
  1270.         if ( pPrinterPB->readDrvr.ctl != NULL )
  1271.         {
  1272.             ctlLocal = pPrinterPB->readDrvr.ctl;
  1273.             pPrinterPB->readDrvr.ctl = NULL;
  1274.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal); 
  1275.         }
  1276.         else
  1277.         {
  1278.             IF_DEBUG( DebugStr( "\pReadCompletion() pPrinterPB->readDrvr.ctl == NULL" ) );
  1279.         }
  1280.     }
  1281. }
  1282.  
  1283.  
  1284. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1285.     Name:        WriteCompletion
  1286.  
  1287.     Input Parameters:    
  1288.         pb                        USB parameter block
  1289.         
  1290.     Output Parameters:
  1291.         <none>
  1292.  
  1293.     Description:
  1294.         USB write requests complete here.
  1295.         We dequeue the MacOS DRVR write requests
  1296.  
  1297.         when breaking up transactions we use ioActCount to determine how much remains 
  1298.                 of the original request and where the next request begins
  1299.         if we've failed with a USB error
  1300.             usbActCount indicates how much data has been transferred with the current request
  1301.             and if the retry count hasn't been exceeded
  1302.                 we proceed as if we'd just requested that much in this transactions
  1303.         note the retry count is cumulative for the original client request
  1304.             not for each usb transaction
  1305.  
  1306.     Change History:
  1307.         16 Nov 1998,    oja:        restored missing writeDrvr.ctl != NULL
  1308.          4 Nov 1998,    oja:        allow chaining of DRVR calls
  1309.         10 Aug 1998,    oja:        set writeDrvr.ctl to NULL when finished
  1310.         28 Jul 1998,    oja:        breakdown transactions into MAX_USB_TRANSFER_SIZE
  1311.         27 Jul 1998,    oja:        lock memory (UIM doesn't do this properly)
  1312.         20 Jul 1998,    oja:        retry transactions
  1313.         16 Jul 1998,    oja:        clear write pipe, not control pipe
  1314.         28 Feb 1998,    oja:        Original version.
  1315. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1316. static void
  1317. WriteCompletion(USBPB *pb)
  1318. {
  1319.     //    call the user completion routine
  1320.     struct usbPrinterPBStruct
  1321.                     *pPrinterPB =  (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1322.     IOParamPtr     clientParam = pPrinterPB->writeDrvr.pb;
  1323.     DCtlPtr            ctlLocal;
  1324.     OSStatus        err = pb->usbStatus;
  1325.  
  1326. #if MACSBUG_ON_WRITE_COMPLETE
  1327.     Str255    text;
  1328.     sprintf( (char *)text, " PrinterClass Write Complete(%d): %d", pb->usbStatus, pb->usbActCount );
  1329.     text[0] = cstrlen((char *)text); // c2pstr
  1330.     DebugStr( text );
  1331. #endif
  1332.  
  1333.     //    update the amount of data actually transferred
  1334.     clientParam->ioActCount += pb->usbActCount;
  1335.     USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "WriteCompletion - wrote  " , (UInt32)pb->usbActCount );
  1336.  
  1337.     switch( pb->usbStatus )
  1338.     {
  1339.         //
  1340.         //    only retry low level hardware problems
  1341.         //        note: abort transactions will end up here as well
  1342.         //
  1343.     case kUSBLinkErr:
  1344.     case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  1345.     case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  1346.     case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  1347.     case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  1348.     case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  1349.     case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  1350.         if (  --(pPrinterPB->writeRetryCount) > 0 ) 
  1351.         {
  1352.             // we got an error, and we still want to retry, clear any stalls
  1353.             USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "WriteCompletion retry" , pb->usbStatus );
  1354.             USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1355.             pb->usbStatus = noErr;
  1356.         }
  1357.         break;
  1358.     case kUSBAbortedError:                        /* user cancel, or hot unplug */
  1359.         USBClearPipeStallByReference(pPrinterPB->writePipeRef);
  1360.         USBClearPipeStallByReference(pPrinterPB->deviceRef);
  1361.         break;
  1362.         //
  1363.         //    any other error will be reported to the client
  1364.         //
  1365.     default:
  1366.     case noErr:
  1367.         break;
  1368.     }
  1369.  
  1370.     if ( pb->usbStatus == noErr && clientParam->ioActCount < clientParam->ioReqCount )
  1371.     {
  1372.         //
  1373.         //    haven't finish the client's request
  1374.         //        update the pointers and start another bulkOut transaction
  1375.         //
  1376. #if LOCK_MEMORY
  1377.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1378.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass WriteCompletion UnlockMem failed" ) );
  1379. #endif
  1380.         pb->usbBuffer = clientParam->ioBuffer + clientParam->ioActCount;
  1381.         pb->usbReqCount = clientParam->ioReqCount - clientParam->ioActCount;
  1382. #if MAX_USB_TRANSFER_SIZE
  1383.         if ( pb->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1384.             pb->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1385. #endif
  1386. #if DOUBLE_BUFFER
  1387.         //
  1388.         //    make sure we have enough room in our buffer
  1389.         //    then copy the user data into our page aligned buffer
  1390.         //
  1391.         if ( pb->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1392.             pb->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1393.         BlockCopy( pb->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, pb->usbReqCount );
  1394.         pb->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1395. #endif
  1396. #if LOCK_MEMORY
  1397.         err = LockMemory( pb->usbBuffer, pb->usbReqCount );
  1398.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass WriteCompletion LockMem failed" ) );
  1399.         if ( err == noErr )
  1400. #endif
  1401.             err = USBBulkWrite( pb );
  1402.         if ( immediateError(err) )
  1403.         {
  1404.             USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "WriteCompletion finish immed err" , err );
  1405.  
  1406.             pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1407.             if ( pPrinterPB->writeDrvr.ctl != NULL )
  1408.             {
  1409.                 ctlLocal = pPrinterPB->writeDrvr.ctl;
  1410.                 pPrinterPB->writeDrvr.ctl = NULL;
  1411.                 CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, err, clientParam, ctlLocal ); 
  1412.             }
  1413.         }
  1414.     }
  1415.     else
  1416.     {
  1417.         //
  1418.         //        either we have an error which we're not retrying
  1419.         //            or we successfully completed
  1420.         //
  1421. #if LOCK_MEMORY
  1422.         err = UnlockMemory( pb->usbBuffer, pb->usbReqCount );
  1423.         IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass WriteCompletion concluded UnlockMem failed" ) );
  1424. #endif
  1425.         IF_DEBUG( if (pb->usbStatus != noErr) USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "WriteCompletion Error" , pb->usbStatus ) );
  1426.         pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1427.         USBExpertStatus(pb->usbReference, "\p" kStrPrinterClass "writeDrvr.ctl = " , (UInt32)pPrinterPB->writeDrvr.ctl );
  1428.         if ( pPrinterPB->writeDrvr.ctl != NULL )
  1429.         {
  1430.             ctlLocal = pPrinterPB->writeDrvr.ctl;
  1431.             pPrinterPB->writeDrvr.ctl = NULL;
  1432.             CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, ctlLocal ); 
  1433.         }
  1434.         else
  1435.         {
  1436.             IF_DEBUG( DebugStr( "\pWriteCompletion() pPrinterPB->writeDrvr.ctl == NULL" ) );
  1437.         }
  1438.     }
  1439. }
  1440.  
  1441. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1442.     Name:        QueueRead
  1443.  
  1444.     Input Parameters:    
  1445.         pb                        MacOS device manager parameter block
  1446.         ctl                    device manager dCtl block
  1447.         pPrinterPB            current printing device class's storage
  1448.         
  1449.     Output Parameters:
  1450.         <none>
  1451.  
  1452.     Description:
  1453.         MacOS DRVR read requests are re-queued here to the USB
  1454.         Since we only allow one read request pending at a time, we're able
  1455.         to use the USB refCon to point to our class driver's storage.
  1456.  
  1457.     Change History:
  1458.         16 Nov 1998,    oja:        added LOCKMEMORY
  1459.         28 Feb 1998,    oja:        Original version.
  1460. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1461. void
  1462. QueueRead( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1463. {    
  1464.     OSStatus    err;
  1465.     USBPB        *usbprint = &pPrinterPB->in;
  1466.     
  1467. #if MACSBUG_ON_READ
  1468.     Str255    text;
  1469.  
  1470.     sprintf( (char *)text, " PrinterClass Read: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1471.     text[0] = cstrlen((char *)text); // c2pstr
  1472.     USBExpertStatus(usbprint->usbReference, text, usbprint->usbStatus );
  1473. //    DebugStr( text );
  1474. #endif
  1475.  
  1476.     pb->ioActCount = 0;        // nothing transfered yet
  1477.     if ( pPrinterPB->terminating )
  1478.         pb->ioResult = abortErr;
  1479.     else
  1480.     {
  1481.  
  1482.         pPrinterPB->readRetryCount = 5;
  1483.         pPrinterPB->readDrvr.pb= pb;
  1484.         pPrinterPB->readDrvr.ctl = ctl;
  1485.         if (( pPrinterPB->readPipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1486.         {
  1487.             SetNullUSBParamBlock( pPrinterPB->readPipeRef,  usbprint );
  1488.             USBExpertStatus(usbprint->usbReference, "\pSet up to do bulk read", pb->ioReqCount );
  1489.             usbprint->usbActCount = 0;
  1490.             usbprint->usbBuffer = pb->ioBuffer;
  1491.             usbprint->usbReqCount = pb->ioReqCount;
  1492.  
  1493. #if MAX_USB_TRANSFER_SIZE
  1494.             //
  1495.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1496.             //        or there is an error which can't be retried
  1497.             //
  1498.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1499.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1500. #endif
  1501. #if DOUBLE_BUFFER
  1502.             //
  1503.             //    make sure we have enough room in our buffer
  1504.             //    then copy the user data into our page aligned buffer
  1505.             //
  1506.             if ( usbprint->usbReqCount > pPrinterPB->pageReadAlignedBufferSize )
  1507.                 usbprint->usbReqCount = pPrinterPB->pageReadAlignedBufferSize;
  1508.             usbprint->usbBuffer = pPrinterPB->pageReadAlignedBuffer;
  1509. #endif
  1510.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1511.             usbprint->usbCompletion = (USBCompletion) ReadCompletion;
  1512.             
  1513.             pb->ioResult = ioInProgress;
  1514. #if LOCK_MEMORY
  1515.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1516.             IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass QueueRead LockMem failed" ) );
  1517.             if ( err == noErr )
  1518. #endif
  1519.             err = USBBulkRead( usbprint );
  1520.             if ( immediateError(err) )
  1521.             {
  1522.                 USBExpertStatus(usbprint->usbReference, "\pError doing bulk read",0 );
  1523.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1524.                 pb->ioResult = err;
  1525.             }
  1526.         }
  1527.         else
  1528.         {
  1529.             USBExpertStatus(usbprint->usbReference, "\p" kStrPrinterClass "Read to unopened pipe" , usbprint->usbStatus ) ;
  1530.             pb->ioResult = abortErr;
  1531.         }
  1532.     }
  1533. }
  1534.  
  1535. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1536.     Name:        QueueWrite
  1537.  
  1538.     Input Parameters:    
  1539.         pb                        MacOS device manager parameter block
  1540.         ctl                    device manager dCtl block
  1541.         pPrinterPB            current printing device class's storage
  1542.         
  1543.     Output Parameters:
  1544.         <none>
  1545.  
  1546.     Description:
  1547.         MacOS DRVR write requests are re-queued here to the USB
  1548.         Since we only allow one read request pending at a time, we're able
  1549.         to use the USB refCon to point to our class driver's storage.
  1550.  
  1551.     Change History:
  1552.         28 Feb 1998,    oja:        Original version.
  1553. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1554. void
  1555. QueueWrite( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1556. {
  1557.     OSStatus    err;
  1558.     USBPB        *usbprint = &pPrinterPB->out;
  1559. #if VIRTUAL_MEMORY_CHECK
  1560.     //
  1561.     //    dump the VM table
  1562.     //
  1563.     Str255                        text;
  1564.     LogicalToPhysicalTable    *vmTable;
  1565.     MemoryBlock                    *physical;
  1566.     unsigned long                vmCount,
  1567.                                     vmEntry,
  1568.                                     vmTblLength;
  1569. #endif
  1570.  
  1571. #if MACSBUG_ON_WRITE
  1572.     Str255    text;
  1573.     sprintf( (char *)text, " PrinterClass Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1574.     text[0] = cstrlen((char *)text); // c2pstr
  1575.     USBExpertStatus(usbprint->usbReference, text, usbprint->usbStatus );
  1576. //    DebugStr( text );
  1577. #endif
  1578.  
  1579. #if VIRTUAL_MEMORY_CHECK
  1580.     //
  1581.     //    this check current won't compile without runtime error: need to lock memory, but lock has moved
  1582.     //
  1583.     sprintf( (char *)text, " PrinterClass Write: %d @ %08x", pb->ioReqCount, pb->ioBuffer );
  1584.     text[0] = cstrlen((char *)text); // c2pstr
  1585.     USBExpertStatus(usbprint->usbReference, text, usbprint->usbStatus );
  1586.     
  1587.     vmCount = 127;
  1588.     vmTblLength = (vmCount+1)*sizeof(MemoryBlock);
  1589.     vmTable = (LogicalToPhysicalTable *) NewPtrSys( vmTblLength );
  1590.     LockMemory( vmTable, vmTblLength );
  1591.     LockMemory( &vmCount, sizeof(unsigned long) );
  1592.     vmTable->logical.address = pb->ioBuffer;
  1593.     vmTable->logical.count = pb->ioReqCount;
  1594.     err = GetPhysical( vmTable, &vmCount );
  1595.     
  1596.     if ( err == noErr )
  1597.     {
  1598.         for ( vmEntry = 0, physical = &vmTable->physical[0]; vmEntry < vmCount; ++vmEntry , ++physical)
  1599.         {
  1600.             sprintf( (char *)text, " PrinterClass Write: VM @%08x (%d)", physical->address, physical->count );
  1601.             text[0] = cstrlen((char *)text); // c2pstr
  1602.             USBExpertStatus(usbprint->usbReference, text, usbprint->usbStatus );
  1603.         }
  1604.     }
  1605.     UnlockMemory( vmTable, vmTblLength );
  1606.     UnlockMemory( &vmCount, sizeof(unsigned long) );
  1607. #endif
  1608.     pb->ioActCount = 0;        // nothing transfered yet
  1609.  
  1610.  
  1611.     usbprint->usbStatus = noErr;    // forget about abort and things from previous writes
  1612.     if ( pPrinterPB->terminating )
  1613.         pb->ioResult = abortErr;
  1614.     else
  1615.     {
  1616.         pPrinterPB->writeRetryCount = 5;
  1617.         pPrinterPB->writeDrvr.pb = pb;
  1618.         pPrinterPB->writeDrvr.ctl = ctl;
  1619.         if (( pPrinterPB->writePipeRef != NULL ) && (pPrinterPB->printerConfigured))
  1620.         {
  1621.             SetNullUSBParamBlock( pPrinterPB->writePipeRef,  usbprint );
  1622.             USBExpertStatus(usbprint->usbReference, "\pSet up to do bulk write", pb->ioReqCount );
  1623.             usbprint->usbActCount = 0;
  1624.             usbprint->usbBuffer = pb->ioBuffer;
  1625.             usbprint->usbReqCount = pb->ioReqCount;
  1626. #if MAX_USB_TRANSFER_SIZE
  1627.             //
  1628.             //    the completion routine will queue another BulkWrite until we exhaust the data
  1629.             //        or there is an error which can't be retried
  1630.             //
  1631.             if ( usbprint->usbReqCount > MAX_USB_TRANSFER_SIZE )
  1632.                 usbprint->usbReqCount = MAX_USB_TRANSFER_SIZE;
  1633. #endif
  1634. #if DOUBLE_BUFFER
  1635.             //
  1636.             //    make sure we have enough room in our buffer
  1637.             //    then copy the user data into our page aligned buffer
  1638.             //
  1639.             if ( usbprint->usbReqCount > pPrinterPB->pageWriteAlignedBufferSize )
  1640.                 usbprint->usbReqCount = pPrinterPB->pageWriteAlignedBufferSize;
  1641.             BlockCopy( usbprint->usbBuffer, pPrinterPB->pageWriteAlignedBuffer, usbprint->usbReqCount );
  1642.             usbprint->usbBuffer = pPrinterPB->pageWriteAlignedBuffer;
  1643. #endif
  1644.             usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1645.             usbprint->usbCompletion = (USBCompletion) WriteCompletion;
  1646.              
  1647.             pb->ioResult = ioInProgress;
  1648.     
  1649. #if LOCK_MEMORY
  1650.             err = LockMemory( usbprint->usbBuffer, usbprint->usbReqCount );
  1651.             IF_DEBUG( if ( err != noErr ) DebugStr( "\pPrinterClass QueueWrite LockMem failed" ) );
  1652.             if ( err == noErr )
  1653. #endif
  1654.                 err = USBBulkWrite( usbprint );
  1655.             if ( immediateError(err) )
  1656.             {
  1657.                 USBExpertStatus(usbprint->usbReference, "\pError doing bulk write",0 );
  1658.                 IF_DEBUG( DebugStr( USBStatusStr(err, kPString) ) );
  1659.                 pb->ioResult = err;
  1660.             }
  1661.             //
  1662.             //    note our logging is one write for each the client request
  1663.             //        not one write for each usb transaction
  1664.             //
  1665.             LOGGING( fwrite( pb->ioBuffer, sizeof(char), pb->ioReqCount, logfile ) );
  1666.         }
  1667.         else
  1668.         {
  1669.             USBExpertStatus(usbprint->usbReference, "\p" kStrPrinterClass "Write to unopened pipe" , usbprint->usbStatus );
  1670.             pb->ioResult = abortErr;
  1671.         }
  1672.     }
  1673. }
  1674.  
  1675.  
  1676. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1677.     Name:        Abort
  1678.  
  1679.     Input Parameters:    
  1680.         refNum            DRVR refnum
  1681.         pPrinterPB        current printing device class's storage
  1682.  
  1683.     Output Parameters:
  1684.         
  1685.     Description:
  1686.         Asynchronous completion.
  1687.         Note: USBAbortPipeByReference can leave the data toggle in the wrong state.
  1688.                 We need to abort both pipes, and then the client must soft reset the printer
  1689.                 to get the printer's data toggles correct.
  1690.         We prematurely call completion routines for active i/o so that CloseDriverSync
  1691.             will not hang the system after an abort, including hot unplug. This works out okay,
  1692.             since the request will be dequeued now, and when the i/o actually terminates
  1693.             the system will be called with an invalid queue element and then reject this second
  1694.             attempt to dequeue the i/o.
  1695.  
  1696.     Change History:
  1697.          4 Aug 1998,    oja:        abort both pipes, call completion routines
  1698.         28 Feb 1998,    oja:        Original version.
  1699. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1700. OSStatus
  1701. Abort( DriverRefNum refNum, struct usbPrinterPBStruct *pPrinterPB )
  1702. {
  1703.     OSStatus        err = noErr;
  1704.  
  1705.  
  1706.     refNum = 0;    // unused
  1707.     //
  1708.     //    if there's any pending io this will call the completion routine
  1709.     //
  1710.     err = USBAbortPipeByReference( pPrinterPB->writePipeRef );
  1711.     err = USBAbortPipeByReference( pPrinterPB->readPipeRef );
  1712.  
  1713.     if ( pPrinterPB->out.usbCompletion != (USBCompletion) NULL )
  1714.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->writeDrvr.pb, pPrinterPB->writeDrvr.ctl ); 
  1715.     if ( pPrinterPB->in.usbCompletion != (USBCompletion) NULL )
  1716.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, abortErr, pPrinterPB->readDrvr.pb, pPrinterPB->readDrvr.ctl ); 
  1717.     return err;
  1718. }
  1719.  
  1720.  
  1721. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1722.     Name:        CompletionProc
  1723.  
  1724.     Input Parameters:    
  1725.         pb                    USB param block ptr
  1726.     
  1727.     Output Parameters:
  1728.         
  1729.     Description:
  1730.         Asynchronous completion routine for DRVR requests.
  1731.  
  1732.     Change History:
  1733.         10 Aug 1998,    oja:        if error, do not set clientParam's ioResult
  1734.                                             explicitly (wait for JIODone)
  1735.         11 Jun 1998,    oja:        Original version.
  1736. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1737. static void 
  1738. CompletionProc(USBPB *pb)
  1739. {
  1740.     //    call the user completion routine
  1741.     struct usbPrinterPBStruct
  1742.                     *pPrinterPB = (struct usbPrinterPBStruct    *) pb->usbRefcon;
  1743.     IOParamPtr     clientParam = pPrinterPB->statusDrvr.pb;
  1744.  
  1745.     clientParam->ioActCount = pb->usbActCount;
  1746.  
  1747.     if ( pb->usbStatus != noErr ) 
  1748.     {
  1749.         USBClearPipeStallByReference(pb->usbReference);  // we got an error, try to clear any stalls
  1750.  
  1751.         IF_DEBUG( USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass "CompletionProc Error" , pb->usbStatus ) );
  1752.         IF_DEBUG( USBExpertStatus(pPrinterPB->deviceRef, USBStatusStr(pb->usbStatus, kPString) , pb->usbStatus ) );
  1753.     }
  1754.  
  1755.     pb->usbCompletion = (USBCompletion) NULL;    // checked by Finalize
  1756.     if ( pPrinterPB->statusDrvr.ctl != NULL )
  1757.         CallUniversalProc( LMGetJIODone(), uppIODoneProcInfo, pb->usbStatus, clientParam, pPrinterPB->statusDrvr.ctl ); 
  1758. }
  1759.  
  1760. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1761.     Name:        CentronicsStatus
  1762.  
  1763.     Input Parameters:    
  1764.         pb                        MacOS device manager parameter block
  1765.         ctl                    device manager dCtl block
  1766.         pPrinterPB            current printing device class's storage
  1767.  
  1768.     Output Parameters:
  1769.         pStatusByte        
  1770.         
  1771.     Description:
  1772.         setup the device request for a USB printer class request one byte status.
  1773.  
  1774.     Change History:
  1775.         29 Jun 1998,    oja:        called from StatusControlRequests, change params
  1776.         26 Jun 1998,    oja:        changed params to be consistent w/ Read & Write
  1777.         11 Jun 1998,    oja:        Original version.
  1778. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1779. static void
  1780. CentronicsStatus( USBPB *usbprint, Ptr buffer, short interfaceNumber )
  1781. {
  1782.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1783.  
  1784.     usbprint->usb.cntl.BRequest = kUSBPrintClassGetCentronicsStatus;
  1785.     usbprint->usb.cntl.WValue = 0;
  1786.     usbprint->usb.cntl.WIndex = interfaceNumber;
  1787.  
  1788.     usbprint->usbReqCount = 1;
  1789.     usbprint->usbBuffer = buffer;
  1790. }
  1791.  
  1792. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1793.     Name:        SoftReset
  1794.  
  1795.     Input Parameters:    
  1796.         usbprint                USB param block
  1797.         interfaceNumber
  1798.  
  1799.     Output Parameters:
  1800.         
  1801.     Description:
  1802.         Setup the device request for a USB printer class request soft reset.
  1803.  
  1804.     Change History:
  1805.         29 Jun 1998,    oja:        called from StatusControlRequests, change params
  1806.         26 Jun 1998,    oja:        changed params to be consistent w/ Read & Write
  1807.         11 Jun 1998,    oja:        Original version.
  1808. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1809. void
  1810. SoftReset( USBPB *usbprint, short interfaceNumber )
  1811. {
  1812.     usbprint->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBClass, kUSBOther);
  1813.  
  1814.     usbprint->usb.cntl.BRequest = kUSBPrintClassSoftReset;
  1815.     usbprint->usb.cntl.WValue = 0;
  1816.     usbprint->usb.cntl.WIndex = interfaceNumber;
  1817.  
  1818.     usbprint->usbReqCount = 0;
  1819.     usbprint->usbBuffer = NULL;
  1820.  
  1821. }
  1822.  
  1823. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1824.     Name:        CapabilityRequest
  1825.  
  1826.     Input Parameters:    
  1827.         usbprint            USB parameter block
  1828.         p                    result pointer
  1829.         length            amount of data allocated
  1830.         config
  1831.         interfaceNum
  1832.         alternateSetting
  1833.         
  1834.  
  1835.     Output Parameters:
  1836.         p                    result pointer
  1837.         length            amount of data allocated
  1838.         
  1839.     Description:
  1840.         setup the device request for a USB printer class request 1284 id string.
  1841.  
  1842.     Change History:
  1843.         29 Jun 1998,    oja:        called from StatusControlRequests, change params
  1844.         26 Jun 1998,    oja:        changed params to be consistent w/ Read & Write
  1845.         11 Jun 1998,    oja:        Original version.
  1846. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1847. void
  1848. CapabilityRequest( USBPB *pb, Ptr p, long length, short configValue, short interfaceNumber, short alternateSetting  )
  1849. {
  1850.  
  1851.     pb->usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBIn, kUSBClass, kUSBInterface);
  1852.  
  1853.     pb->usb.cntl.BRequest = kUSBPrintClassGetDeviceID;
  1854.     pb->usb.cntl.WValue = configValue;        // configuration
  1855.     pb->usb.cntl.WIndex = (interfaceNumber<<8) | alternateSetting;
  1856.  
  1857.     pb->usbReqCount = length;
  1858.     pb->usbBuffer = p;
  1859.  
  1860. }
  1861.  
  1862. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1863.     Name:        StatusControlRequests
  1864.  
  1865.     Input Parameters:    
  1866.         pb                        MacOS device manager parameter block
  1867.         ctl                    device manager dCtl block
  1868.         pPrinterPB            current printing device class's storage
  1869.  
  1870.     Output Parameters:
  1871.         
  1872.     Description:
  1873.         Asynchronous completion.
  1874.  
  1875.     Change History:
  1876.         26 Jun 1998,    oja:        changed params to be consistent w/ Read & Write
  1877.         11 Jun 1998,    oja:        Original version.
  1878. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1879.  
  1880. void
  1881. ControlStatusRequests( IOParamPtr pb, DCtlPtr ctl, struct usbPrinterPBStruct *pPrinterPB )
  1882. {
  1883.  
  1884.     //
  1885.     //    queue a transaction to retrieve the centronics status
  1886.     //
  1887.     OSStatus        err;
  1888.     USBPB            *usbprint = &pPrinterPB->pb;
  1889.     Boolean        dosomething = false;
  1890.     
  1891. #if DEBUG
  1892.     Str255        text;
  1893.  
  1894.     sprintf( (char *)text, " PrinterClass ControlStatus: %d", ((CntrlParam *) pb)->csCode );
  1895.     text[0] = cstrlen((char *)text); // c2pstr
  1896.     USBExpertStatus(usbprint->usbReference, text, usbprint->usbStatus );
  1897. #endif
  1898.  
  1899.     switch( ((CntrlParam *) pb)->csCode )
  1900.     {
  1901.     case kDrvrCentronicsStatus:
  1902.         dosomething = true;
  1903.         CentronicsStatus( usbprint,  *((Ptr *)((CntrlParam *) pb)->csParam), pPrinterPB->interfaceNumber );
  1904.         break;
  1905.     case kDrvr1284IdString:
  1906.         dosomething = true;
  1907.         CapabilityRequest( usbprint,
  1908.                                 *((Ptr *)((CntrlParam *) pb)->csParam),
  1909.                                 *((long *) &((CntrlParam *) pb)->csParam[4]),
  1910.                                 pPrinterPB->configurationNumber,        // configuration
  1911.                                 pPrinterPB->interfaceNumber,
  1912.                                 pPrinterPB->alternateSetting);
  1913.         break;
  1914.     case kDrvrSoftReset:
  1915.         dosomething = true;
  1916.         SoftReset( usbprint, pPrinterPB->interfaceNumber );
  1917.         break;
  1918.     default:
  1919.         break;
  1920.     }
  1921.  
  1922.     if ( !dosomething )
  1923.         pb->ioResult = paramErr;
  1924.     else
  1925.     {
  1926.         SetNullUSBParamBlock(pPrinterPB->deviceRef,  usbprint );
  1927.         usbprint->usbBuffer = 0;
  1928.         usbprint->usbActCount = 0;
  1929.         usbprint->usbReqCount = 0;
  1930.         usbprint->usbCompletion = (USBCompletion)CompletionProc;
  1931.         usbprint->usbRefcon = (unsigned long) pPrinterPB;
  1932.     
  1933.         pb->ioResult = ioInProgress;
  1934.         pPrinterPB->statusDrvr.pb = pb;
  1935.         pPrinterPB->statusDrvr.ctl = ctl;
  1936.     
  1937.         err = USBDeviceRequest(usbprint);
  1938.         if(immediateError(err))
  1939.         {
  1940.             USBExpertFatalError(usbprint->usbReference, err, "\p" kStrPrinterClass "StatusControlRequests", 0);
  1941.             pb->ioResult = err;
  1942.         }
  1943.     }
  1944. }
  1945.  
  1946.  
  1947. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1948.     Name:        PrinterDeviceCompletionProc
  1949.  
  1950.     Input Parameters:    
  1951.         pb                refCon tells which state we're completing
  1952.  
  1953.     Output Parameters:
  1954.         <none>
  1955.         
  1956.     Description:
  1957.         Complete asynch transactions initiated by PrinterDeviceInitiateTransaction.
  1958.  
  1959.     Change History:
  1960.         17 Aug 1998,    oja:        don't retry high level errors (support hot unplug of root hub)
  1961.         20 Jul 1998,    oja:        clear pipe stall before retrying
  1962.         15 May 1998,    oja:        added missing break for GetCapabilityString
  1963.                                         reworked GetFullConfiguration to properly handle case
  1964.                                             where there's only one interface
  1965.         26 Mar 1998,    oja:        set info 1 to DEBUG StateStr
  1966.                                         (distinguishes completion from initiate)
  1967.         28 Feb 1998,    oja:        Original version.
  1968. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  1969.  
  1970. static void 
  1971. PrinterDeviceCompletionProc(USBPB *pb)
  1972. {
  1973.     register struct usbPrinterPBStruct *pPrinterPB;
  1974.     OSStatus                                        err;
  1975.  
  1976.     
  1977.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  1978.  
  1979.     pPrinterPB->transDepth--; 
  1980.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  1981.     {
  1982.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, "\p" kStrPrinterClass "CompletionProc Illegal Transaction Depth", pPrinterPB->transDepth );
  1983.     }
  1984.  
  1985.     IF_DEBUG( USBExpertStatus(pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString) , 1 ) );
  1986.  
  1987.     pPrinterPB->delayInProgress = false;
  1988.     
  1989.     if ( pPrinterPB->terminating )
  1990.     {
  1991.         //    if we've been hot unplugged
  1992.         //        don't startup any new transactions
  1993.         //     allow PrintDriverFinalize to continue
  1994.         pPrinterPB->pb.usbStatus = kUSBAbortedError;
  1995.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  1996.     }
  1997.     
  1998.  
  1999.     switch( pPrinterPB->pb.usbStatus )
  2000.     {
  2001.         case kUSBPending:
  2002.         case noErr:
  2003.             pPrinterPB->pb.usbRefcon &= ~kRetryTransaction;
  2004.             pPrinterPB->retryCount = kPrinterRetryCount;
  2005.             break;
  2006.         case kUSBLinkErr:
  2007.         case kUSBCRCErr:                                /*  Pipe stall, bad CRC */
  2008.         case kUSBBitstufErr:                            /*  Pipe stall, bitstuffing */
  2009.         case kUSBDataToggleErr:                        /*  Pipe stall, Bad data toggle */
  2010.         case kUSBNotRespondingErr:                    /*  Pipe stall, No device, device hung */
  2011.         case kUSBPIDCheckErr:                        /*  Pipe stall, PID CRC error */
  2012.         case kUSBWrongPIDErr:                        /*  Pipe stall, Bad or wrong PID */
  2013.         
  2014.             USBClearPipeStallByReference(pPrinterPB->deviceRef);  // we got an error, try to clear any stalls
  2015.             USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass "    retry", pPrinterPB->pb.usbStatus);
  2016.             
  2017.             // clear out the transaction pending flag
  2018.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2019.             pPrinterPB->pb.usbRefcon |= kRetryTransaction;
  2020.             pPrinterPB->retryCount--;
  2021.             if (!pPrinterPB->retryCount)
  2022.             {
  2023.                 USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, "\p" kStrPrinterClass "Retry failed", pPrinterPB->pb.usbRefcon & ~kRetryTransaction);
  2024.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2025.             } 
  2026.             else 
  2027.             {
  2028.                 pPrinterPB->pb.usbStatus = noErr;             // let's retry one more time
  2029.             }
  2030.             break;
  2031.             
  2032.         case kUSBAbortedError:                        /* user cancel, or hot unplug */
  2033.         default:
  2034.             // clear out the transaction pending flag
  2035.             pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  2036.             pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2037.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2038.             break;
  2039.     }
  2040.  
  2041.     if (pPrinterPB->pb.usbRefcon & kTransactionPending)             
  2042.     {            
  2043.         int    length;
  2044.     
  2045.         //
  2046.         //    advance to the next state
  2047.         //
  2048.         pPrinterPB->pb.usbRefcon &= ~(kTransactionPending + kReturnFromDriver);
  2049.         switch(pPrinterPB->pb.usbRefcon)
  2050.         {
  2051.             case kFindInterface_bidirectional:
  2052.                 USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2053.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2054.                 {
  2055.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2056.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2057.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2058.                     {
  2059.                         USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"Found bidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2060.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2061.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2062.                         pPrinterPB->printerProtocol = kUSBPrinterBidirectionalProtocol;
  2063.                         if (pPrinterPB->pInterfaceDescriptor)
  2064.                         {
  2065.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2066.                             {
  2067.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2068.                             }
  2069.                             else
  2070.                             {
  2071.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindInterface_Bidirectional didn't find the right interface", 0);
  2072.                             }
  2073.                         }
  2074.                         else
  2075.                         {
  2076.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2077.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2078.                         }
  2079.                     }
  2080.                 }
  2081.                 else
  2082.                 {
  2083.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2084.                     {
  2085.                         USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"Bidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2086.                         pPrinterPB->pb.usbRefcon = kFindInterface_unidirectional;
  2087.                     }
  2088.                     else
  2089.                     {
  2090.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindInterface_bidirectional failed", 0);
  2091.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2092.                     }
  2093.                 }
  2094.                 break;
  2095.                 
  2096.             case kFindInterface_unidirectional:
  2097.                 USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"kFindInterface_bidirectional completed", pPrinterPB->pb.usb.cntl.WIndex);
  2098.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2099.                 {
  2100.                     if ((pPrinterPB->pb.usbClassType == kUSBPrintingClass) && 
  2101.                         (pPrinterPB->pb.usbSubclass == kUSBPrinterSubclass) &&
  2102.                         (pPrinterPB->pb.usbProtocol == kUSBPrinterBidirectionalProtocol))
  2103.                     {
  2104.                         USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"Found unidirection interface at alt setting ", pPrinterPB->pb.usbOther);
  2105.                         pPrinterPB->pb.usbRefcon = kOpenDevice;
  2106.                         pPrinterPB->configurationNumber = pPrinterPB->pb.usb.cntl.WValue;
  2107.                         pPrinterPB->alternateSetting = pPrinterPB->pb.usbOther;
  2108.                         pPrinterPB->printerProtocol = kUSBPrinterUnidirectionalProtocol;
  2109.                         if (pPrinterPB->pInterfaceDescriptor)
  2110.                         {
  2111.                             if (pPrinterPB->interfaceNumber == pPrinterPB->pb.usb.cntl.WIndex)
  2112.                             {
  2113.                                 pPrinterPB->pb.usbRefcon = kSetInterface;
  2114.                             }
  2115.                             else
  2116.                             {
  2117.                                 USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindInterface_Unidirectional didn't find the right interface", 0);
  2118.                             }
  2119.                         }
  2120.                         else
  2121.                         {
  2122.                             pPrinterPB->pb.usbRefcon = kOpenDevice;
  2123.                             pPrinterPB->interfaceNumber = pPrinterPB->pb.usb.cntl.WIndex;
  2124.                         }
  2125.                     }
  2126.                 }
  2127.                 else
  2128.                 {
  2129.                     if ( pPrinterPB->pb.usbStatus == kUSBNotFound )
  2130.                     {
  2131.                         USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"Unidirectional interface was not found", pPrinterPB->pb.usb.cntl.WIndex);
  2132.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2133.                     }
  2134.                     else
  2135.                     {
  2136.                         USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindInterface_unidirectional failed", 0);
  2137.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2138.                     }
  2139.                 }
  2140.                 break;
  2141.                 
  2142.             case kOpenDevice:
  2143.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2144.                 {
  2145.                     USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"kOpenDevice completed", pPrinterPB->pb.usbStatus);
  2146.                     pPrinterPB->pb.usbRefcon = kNewInterfaceRef;
  2147.                 }
  2148.                 else
  2149.                 {
  2150.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kOpenDevice failed", 0);
  2151.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2152.                 }
  2153.                 break;
  2154.                 
  2155.             case kNewInterfaceRef:
  2156.                 USBExpertStatus(pPrinterPB->deviceRef, "\p"kStrPrinterClass"kNewInterfaceRef completed", pPrinterPB->pb.usbReference);
  2157.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2158.                 {
  2159.                     pPrinterPB->interfaceRef = pPrinterPB->pb.usbReference;
  2160.                     pPrinterPB->pb.usbRefcon = kSetInterface;
  2161.                 }
  2162.                 else
  2163.                 {
  2164.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kNewInterfaceRef failed", 0);
  2165.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2166.                 }
  2167.                 break;
  2168.             
  2169.             case kSetInterface:
  2170.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kSetInterface completed", 0);
  2171.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2172.                 {
  2173.                     pPrinterPB->pb.usbRefcon = kConfigureInterface;
  2174.                 }
  2175.                 else
  2176.                 {
  2177.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kSetInterface failed", 0);
  2178.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2179.                 }
  2180.                 break;
  2181.             
  2182.             case kConfigureInterface:
  2183.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kConfigureInterface completed, pipes = ", pPrinterPB->pb.usbOther);
  2184.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2185.                 {
  2186.                     pPrinterPB->pipeCount = pPrinterPB->pb.usbOther;
  2187.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2188.                 }
  2189.                 else
  2190.                 {
  2191.                     USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kConfigureInterface failed", 0);
  2192.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2193.                 }
  2194.                 break;
  2195.             
  2196.             case kGetCapabilityString:
  2197.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kGetCapabilityString completed", pPrinterPB->pb.usbStatus);
  2198.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2199.                 {
  2200.                     //
  2201.                     //    In the short term (fall '98) several vendors are planning on shipping 
  2202.                     //        devices with a parallel port and using the Lucent USS-720 USB-to-parallel hardware.
  2203.                     //    Unfortunately this isn't an ideal solution from the USB perspective:
  2204.                     //        users can leave the printer off while the cable responds that there's
  2205.                     //        a printer connected. Then we have no way of using the DEVICE_ID
  2206.                     //        string to tag the printer and register it.
  2207.                     //    To alleviate this situation, we repeatedly poll the USS-720 if the DEVICE_ID
  2208.                     //        string is null. Every few seconds we'll retry this state.
  2209.                     //    At some point the user wants to print and switches on the printer. The class
  2210.                     //    driver then picks up from here and registers the device properly.
  2211.                     //
  2212.                     length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2213.                     if ( IsLucentCable( &pPrinterPB->deviceDescriptor ) && pPrinterPB->pb.usbActCount == 0 )
  2214.                         pPrinterPB->pb.usbRefcon = kDelayGetCapability;
  2215.                     else
  2216.                         pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2217.                 }
  2218.                 else
  2219.                 {
  2220.                     if ( pPrinterPB->pb.usbStatus == kUSBOverRunErr )
  2221.                     {
  2222.                         //
  2223.                         //    if we've haven't managed to read the whole capability string
  2224.                         //        we need to allocate memory and read it in by initiating kGetFullCapabilityString
  2225.                         //
  2226.                         length = pPrinterPB->pCapabilityString[1] | (pPrinterPB->pCapabilityString[0] << 8);
  2227.     
  2228.                         if ( length > sizeof(pPrinterPB->capability) &&
  2229.                                 pPrinterPB->pb.usbRefcon == kGetCapabilityString )
  2230.                             pPrinterPB->pb.usbRefcon = kAllocateCapabilityMem;
  2231.                     }
  2232.                     else
  2233.                     {
  2234.                         USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kGetCapabilityString failed", 0);
  2235.                         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2236.                     }
  2237.                 }
  2238.                 break;
  2239.                 
  2240.             case kDelayGetCapability:
  2241.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kDelayGetCapability completed", pPrinterPB->pb.usbStatus);
  2242.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2243.                 {
  2244.                     pPrinterPB->pb.usbRefcon = kGetCapabilityString;
  2245.                 }
  2246.                 else
  2247.                 {
  2248.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kDelayGetCapability failed", 0);
  2249.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2250.                 }
  2251.                 break;
  2252.                 
  2253.             case kAllocateCapabilityMem:
  2254.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kAllocateCapabilityMem completed", pPrinterPB->pb.usbStatus);
  2255.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2256.                 {
  2257.                     pPrinterPB->pCapabilityString = pPrinterPB->pb.usbBuffer;
  2258.                     pPrinterPB->pb.usbRefcon = kGetFullCapabilityString;    
  2259.                 }
  2260.                 else
  2261.                 {
  2262.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kAllocateCapabilityMem failed", 0);
  2263.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2264.                 }
  2265.                 break;
  2266.             
  2267.             case kGetFullCapabilityString:
  2268.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kGetFullCapabilityString completed", pPrinterPB->pb.usbStatus);
  2269.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2270.                 {
  2271.                     pPrinterPB->pb.usbRefcon = kGetInterface;
  2272.                 }
  2273.                 else
  2274.                 {
  2275.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kGetFullCapabilityString failed", 0);
  2276.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2277.                 }
  2278.                 break;
  2279.                 
  2280.             case kGetInterface:
  2281.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kGetInterface completed", pPrinterPB->pb.usbStatus);
  2282.                 if (( pPrinterPB->pb.usbStatus == noErr ) && (pPrinterPB->whichAltInterface == pPrinterPB->alternateSetting))
  2283.                 {
  2284.                     pPrinterPB->pb.usbRefcon = kFindBulkOutPipe;
  2285.                 }
  2286.                 else
  2287.                 {
  2288.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kGetInterface - wrong interface selected", pPrinterPB->whichAltInterface);
  2289.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2290.                 }
  2291.                 break;
  2292.  
  2293.             case kFindBulkOutPipe:
  2294.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kFindBulkOutPipe completed", pPrinterPB->pb.usbReference);
  2295.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2296.                 {
  2297.                     pPrinterPB->writePipeRef = pPrinterPB->pb.usbReference;             // remember the ref
  2298.                     pPrinterPB->out = pPrinterPB->pb;                                        // copy the paramblock
  2299.                     pPrinterPB->out.usbCompletion =  (USBCompletion) NULL;            // for finalize
  2300.  
  2301.                     if ( pPrinterPB->printerProtocol == kUSBPrinterBidirectionalProtocol )
  2302.                         pPrinterPB->pb.usbRefcon = kFindBulkInPipe;
  2303.                     else
  2304.                         pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2305.                 }
  2306.                 else
  2307.                 {
  2308.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindBulkOutPipe failed", 0);
  2309.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2310.                 }
  2311.                 break;
  2312.                 
  2313.             case kFindBulkInPipe:
  2314.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kFindBulkInPipe completed", pPrinterPB->pb.usbReference);
  2315.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2316.                 {
  2317.                     pPrinterPB->readPipeRef = pPrinterPB->pb.usbReference;
  2318.                     pPrinterPB->in = pPrinterPB->pb;                                            // copy the paramblock
  2319.                     pPrinterPB->in.usbCompletion =  (USBCompletion) NULL;                // for finalize
  2320.  
  2321.                     pPrinterPB->pb.usbRefcon = kTaskTimeRequired;
  2322.                 }
  2323.                 else
  2324.                 {
  2325.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "kFindBulkInPipe failed", 0);
  2326.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2327.                 }
  2328.                 break;
  2329.                 
  2330.             case kTaskTimeRequired:
  2331.                 USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kTaskTimeRequired completed (now at task time)", pPrinterPB->pb.usbReference);
  2332.             //
  2333.             //    once we know what device we're dealing with
  2334.             //        open the i/o channel(s) to the device
  2335.             //        and enter it in the name registry
  2336.             //
  2337.                 err = InstallDrivers( pPrinterPB );
  2338.                 if ( err == noErr )
  2339.                 {
  2340.                     USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kTaskTimeRequired - drivers installed", pPrinterPB->pb.usbReference);
  2341.                     err = RegisterDevice( pPrinterPB );
  2342.                     if ( err == noErr )
  2343.                     {
  2344.                         USBExpertStatus(pPrinterPB->interfaceRef, "\p"kStrPrinterClass"kTaskTimeRequired - RegisterDevice successful", pPrinterPB->pb.usbReference);
  2345.                     }
  2346.                     else
  2347.                     {
  2348.                         USBExpertFatalError(pPrinterPB->interfaceRef, err, "\p" kStrPrinterClass "kTaskTimeRequired - RegisterDevice failed", 0);
  2349.                     }
  2350.                 }
  2351.                 else
  2352.                 {
  2353.                     USBExpertFatalError(pPrinterPB->interfaceRef, err, "\p" kStrPrinterClass "kTaskTimeRequired - InstallDrivers failed", 0);
  2354.                 }
  2355.     
  2356.                 pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;                    // Finalize
  2357.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2358.                 {
  2359.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  2360.                     pPrinterPB->printerConfigured = true;
  2361.                 }
  2362.                 else
  2363.                 {
  2364.                     USBExpertFatalError(pPrinterPB->interfaceRef, pPrinterPB->pb.usbStatus, "\p" kStrPrinterClass "RegisterDevice failed", 0);
  2365.                     pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2366.                 }
  2367.                 break;
  2368.                 
  2369.             case kGetCentronicsStatus:
  2370.                 //
  2371.                 //    if InitiateTransaction fell through on it's kTaskTimeRequired case we'll end up here
  2372.                 //
  2373.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2374.                 {
  2375. #if DEBUG
  2376.                     Str255    text, te;
  2377.                     hexstr( sizeof(char), &pPrinterPB->centronics.b, (char *) te );
  2378.                     sprintf( (char *)text, " PrinterClass Status: %s", te );
  2379.                     text[0] = cstrlen((char *)text); // c2pstr
  2380.                     USBExpertStatus(pPrinterPB->interfaceRef, text, pb->usbStatus );
  2381. #endif
  2382. #if DEBUG
  2383.                     if ( !pPrinterPB->centronics.status.notError )
  2384.                     {
  2385.                         USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass "Error at printer", pPrinterPB->pb.usbStatus);
  2386.                     }
  2387.                     if ( pPrinterPB->centronics.status.paperError )
  2388.                     {
  2389.                         USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass "Check paper", pPrinterPB->pb.usbStatus);
  2390.                     }
  2391.                     if ( !pPrinterPB->centronics.status.select )
  2392.                     {
  2393.                         USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass "printer offline", pPrinterPB->pb.usbStatus);
  2394.                     }
  2395. #endif
  2396.                     pPrinterPB->pb.usbRefcon = kDelayGetCentronicsStatus;
  2397.                 }
  2398.                 break;
  2399.                 
  2400.             case kDelayGetCentronicsStatus:
  2401.                 //
  2402.                 //    loop around continually getting status
  2403.                 //
  2404.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2405.                 {
  2406.                     pPrinterPB->pb.usbRefcon = kGetCentronicsStatus;
  2407.                 }
  2408.                 break;
  2409.             case kNilCompletion:
  2410.             default:
  2411.                 if ( pPrinterPB->pb.usbStatus == noErr )
  2412.                     pPrinterPB->pb.usbRefcon = kUndefined | kReturnFromDriver;
  2413.                 break;
  2414.         }
  2415.     }
  2416.     
  2417.     // did the removal notification get called?  If so, don't start another transaction.  Just exit
  2418.    if (!pPrinterPB->terminating)
  2419.     {
  2420.         if (pPrinterPB->pb.usbStatus == noErr )
  2421.         {
  2422.             if (!(pPrinterPB->pb.usbRefcon & kReturnFromDriver))
  2423.                 PrinterDeviceInitiateTransaction(pb);
  2424.         }
  2425.         else if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  2426.         {
  2427.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, StateStr(pPrinterPB->pb.usbRefcon, kPString), pPrinterPB->pb.usbRefcon);
  2428.             USBExpertFatalError(pPrinterPB->deviceRef, pPrinterPB->pb.usbStatus, USBStatusStr(pPrinterPB->pb.usbStatus, kPString), 0);
  2429.         }
  2430.     }
  2431.     else
  2432.     {
  2433.         pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2434.     }
  2435.     
  2436.     // If we're exiting the driver, then make certain the completion routine is set to NULL
  2437.     // this lets the driver removal task know that there's nothing pending.
  2438.     if ( pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  2439.     {
  2440.         pPrinterPB->pb.usbCompletion    = (USBCompletion) NULL;
  2441.     }
  2442. }
  2443.  
  2444. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2445.     Name:        PrinterDeviceInitiateTransaction
  2446.  
  2447.     Input Parameters:    
  2448.         pb            USB parameter block
  2449.         
  2450.     Output Parameters:
  2451.         
  2452.     Description:
  2453.         Since USB transactions are asynchronous we use the refCon field
  2454.         in the parameter block to implement the following logic via a state machine.
  2455.  
  2456.         Start out by getting the device configuration descriptor
  2457.         If the device has more than one printing interface
  2458.             If a bidirectional interface exists
  2459.                 select it
  2460.             Else
  2461.                 select the (mandatory) unidirectional interface
  2462.         Get the (manadatory) 1284 capability string
  2463.         Open pipes to the BulkOut (and optional BulkIn) endpoints
  2464.         Install read and write drivers in the unit table
  2465.         Using information from the capability string
  2466.             enter the printer in the MacOS name registry.
  2467.         
  2468.  
  2469.     Change History:
  2470.         15 May 1998,    oja:        cleanup error/status messages
  2471.                                         handle setinterface correctly if only one
  2472.                                             interface is available
  2473.         28 Feb 1998,    oja:        Original version.
  2474. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2475. void
  2476. PrinterDeviceInitiateTransaction(USBPB *pb)
  2477. {
  2478.     register struct usbPrinterPBStruct    *pPrinterPB;
  2479.     int                                            length;
  2480.     OSStatus                                        err;
  2481.  
  2482.     pPrinterPB = (struct usbPrinterPBStruct *)(pb);
  2483.     
  2484.     pPrinterPB->transDepth++;
  2485.     if ((pPrinterPB->transDepth < 0) || (pPrinterPB->transDepth > 1))
  2486.     {
  2487.         USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, "\p" kStrPrinterClass "InitiateTransaction illegal transaction depth", 0);
  2488.     }
  2489.     IF_DEBUG( USBExpertStatus( pPrinterPB->deviceRef, StateStr(pPrinterPB->pb.usbRefcon, kPString), 0) );     
  2490.  
  2491.     pPrinterPB->delayInProgress = false;
  2492.     switch(pPrinterPB->pb.usbRefcon & ~kRetryTransaction)
  2493.     {
  2494.         case kFindInterface_bidirectional:
  2495.             USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass"kFindInterface_bidirectional", 0);
  2496.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  2497.             
  2498.             pPrinterPB->pb.usbBuffer = 0;
  2499.             pPrinterPB->pb.usbActCount = 0;
  2500.             pPrinterPB->pb.usbReqCount = 0;
  2501.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  2502.             pPrinterPB->pb.usb.cntl.WValue = 0;
  2503.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  2504.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  2505.             pPrinterPB->pb.usbProtocol = kUSBPrinterBidirectionalProtocol;
  2506.             
  2507.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2508.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2509.             err = USBFindNextInterface(pb);
  2510.             if(immediateError(err))
  2511.             {
  2512.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"kFindInterface_bidirectional - immediate error", err);
  2513.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2514.             }
  2515.             break;
  2516.     
  2517.         case kFindInterface_unidirectional:
  2518.             USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass"kFindInterface_unidirectional", 0);
  2519.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  2520.             
  2521.             pPrinterPB->pb.usbBuffer = 0;
  2522.             pPrinterPB->pb.usbActCount = 0;
  2523.             pPrinterPB->pb.usbReqCount = 0;
  2524.             pPrinterPB->pb.usb.cntl.WIndex = 0;
  2525.             pPrinterPB->pb.usb.cntl.WValue = 0;
  2526.             pPrinterPB->pb.usbClassType = kUSBPrintingClass;
  2527.             pPrinterPB->pb.usbSubclass = kUSBPrinterSubclass;
  2528.             pPrinterPB->pb.usbProtocol = kUSBPrinterUnidirectionalProtocol;
  2529.             
  2530.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2531.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2532.             err = USBFindNextInterface(pb);
  2533.             if(immediateError(err))
  2534.             {
  2535.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"kFindInterface_unidirectional - immediate error", err);
  2536.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2537.             }
  2538.             break;
  2539.     
  2540.         case kOpenDevice:
  2541.             USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass"kOpenDevice", 0);
  2542.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  2543.             
  2544.             pPrinterPB->pb.usbBuffer = 0;
  2545.             pPrinterPB->pb.usbActCount = 0;
  2546.             pPrinterPB->pb.usbReqCount = 0;
  2547.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->configurationNumber;
  2548.             
  2549.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2550.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2551.             err = USBOpenDevice(pb);
  2552.             if(immediateError(err))
  2553.             {
  2554.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"USBOpenDevice - immediate error", err);
  2555.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2556.             }
  2557.             break;
  2558.             
  2559.         case kNewInterfaceRef:
  2560.             USBExpertStatus(pPrinterPB->deviceRef, "\p" kStrPrinterClass"kNewInterfaceRef for interface number", pPrinterPB->interfaceNumber);
  2561.             SetNullUSBParamBlock( pPrinterPB->deviceRef, &pPrinterPB->pb );
  2562.             
  2563.             pPrinterPB->pb.usbBuffer = 0;
  2564.             pPrinterPB->pb.usbActCount = 0;
  2565.             pPrinterPB->pb.usbReqCount = 0;
  2566.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;
  2567.             
  2568.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2569.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2570.             err = USBNewInterfaceRef(pb);
  2571.             if(immediateError(err))
  2572.             {
  2573.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"USBNewInterfaceRef - immediate error", err);
  2574.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2575.             }
  2576.             break;
  2577.             
  2578.  
  2579.         case kSetInterface:
  2580.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kSetInterface to alternate setting", pPrinterPB->alternateSetting);
  2581.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2582.             
  2583.             pPrinterPB->pb.usb.cntl.BMRequestType = USBMakeBMRequestType(kUSBOut, kUSBStandard, kUSBInterface);
  2584.         
  2585.             pPrinterPB->pb.usb.cntl.BRequest = kUSBRqSetInterface;
  2586.             pPrinterPB->pb.usb.cntl.WValue = pPrinterPB->alternateSetting;        // alternate setting
  2587.             pPrinterPB->pb.usb.cntl.WIndex = pPrinterPB->interfaceNumber;        // interface
  2588.         
  2589.             pPrinterPB->pb.usbReqCount = 0;
  2590.             pPrinterPB->pb.usbBuffer = NULL;
  2591.         
  2592.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2593.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2594.             err = USBDeviceRequest(pb);
  2595.             if(immediateError(err))
  2596.             {
  2597.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"kSetInterface - immediate error", err);
  2598.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2599.             }
  2600.             break;
  2601.  
  2602.  
  2603.         case kConfigureInterface:
  2604.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kConfigureInterface for alternate setting", pPrinterPB->alternateSetting);
  2605.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2606.             
  2607.             pPrinterPB->pb.usbBuffer = 0;
  2608.             pPrinterPB->pb.usbActCount = 0;
  2609.             pPrinterPB->pb.usbReqCount = 0;
  2610.             pPrinterPB->pb.usbOther = pPrinterPB->alternateSetting;
  2611.             
  2612.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2613.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2614.             err = USBConfigureInterface(pb);
  2615.             if(immediateError(err))
  2616.             {
  2617.                 USBExpertFatalError(pPrinterPB->pb.usbReference, kUSBInternalErr, "\p"kStrPrinterClass"USBConfigureInterface - immediate error)", err);
  2618.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2619.             }
  2620.             break;
  2621.             
  2622.         case kGetCapabilityString:
  2623.             //
  2624.             //    once the interface (and alternate) is assinged
  2625.             //        we can retreive the 1284 capability string to see what kind of printer
  2626.             //        is attached
  2627.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kGetCapabilityString", 0);
  2628.             pPrinterPB->pCapabilityString = pPrinterPB->capability;
  2629.             GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, sizeof(pPrinterPB->capability) );
  2630.             break;
  2631.             
  2632.         case kDelayGetCapability:
  2633.             //
  2634.             //    USS-720 USB-parallel cable: couldn't get the capability string because the printer is off
  2635.             //        Delay a few seconds and try again.
  2636.             //        Will succeed when the user turns the printer on.
  2637.             //
  2638.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kDelayGetCapability", 0);
  2639.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2640.             
  2641.             pPrinterPB->pb.usbBuffer = 0;
  2642.             pPrinterPB->pb.usbActCount = 0;
  2643.             pPrinterPB->pb.usbReqCount = kUSS720MillisecondDelay;
  2644.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  2645.             
  2646.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2647.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2648.             pPrinterPB->delayInProgress = true;
  2649.             err = USBDelay(&pPrinterPB->pb);
  2650.             if(immediateError(err))
  2651.             {
  2652.                 USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "kDelayGetCapability - immediate error", 0);
  2653.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2654.             }
  2655.             break;
  2656.             
  2657.         case kAllocateCapabilityMem:
  2658.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kAllocateCapabilityMem", 0);
  2659.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2660.             
  2661.             length = pPrinterPB->capability[1] | (pPrinterPB->capability[0]<<8);
  2662.             pPrinterPB->pb.usbBuffer = 0;
  2663.             pPrinterPB->pb.usbActCount = 0;
  2664.             pPrinterPB->pb.usbReqCount = length;
  2665.             pPrinterPB->pb.usbFlags = 0;
  2666.             
  2667.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2668.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2669.             err = USBAllocMem(&pPrinterPB->pb);
  2670.             if(immediateError(err))
  2671.             {
  2672.                 USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "kAllocateCapabilityMem - immediate error", 0);
  2673.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2674.             }
  2675.             break;
  2676.         
  2677.         case kGetFullCapabilityString:
  2678.             //
  2679.             // the capability string was too long to fit in the statically allocated space
  2680.             // need to release this memory when we finalize our driver
  2681.             //
  2682.  
  2683.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kGetFullCapabilityString", 0);
  2684.             if ( pPrinterPB->pCapabilityString )
  2685.                 GetCapability( pPrinterPB, pPrinterPB->pCapabilityString, length );
  2686.             else
  2687.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, "\p" kStrPrinterClass "Can't allocate capability memory", 0);
  2688.             break;
  2689.             
  2690.         case kGetInterface:
  2691.             // failsafe check that we've got the right setup
  2692.             //    it's possible the device didn't respond to our SetInterface
  2693.             GetInterface( &pPrinterPB->pb, &pPrinterPB->whichAltInterface );
  2694.             break;
  2695.  
  2696.         case kFindBulkOutPipe:
  2697.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kFindBulkOutPipe", 0);
  2698.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2699.             
  2700.             pPrinterPB->pb.usbBuffer = 0;
  2701.             pPrinterPB->pb.usbActCount = 0;
  2702.             pPrinterPB->pb.usbReqCount = 0;
  2703.             pPrinterPB->pb.usbFlags = kUSBOut;
  2704.             pPrinterPB->pb.usbClassType = kUSBBulk;
  2705.             
  2706.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2707.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2708.             err = USBFindNextPipe( &pPrinterPB->pb );
  2709.             if (immediateError(err))
  2710.             {
  2711.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, kStrPrinterClass"kFindBulkOutPipe - immediate error", err);
  2712.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2713.             }
  2714.             break;
  2715.             
  2716.         case kFindBulkInPipe:    
  2717.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kFindBulkInPipe", 0);
  2718.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2719.             
  2720.             pPrinterPB->pb.usbBuffer = 0;
  2721.             pPrinterPB->pb.usbActCount = 0;
  2722.             pPrinterPB->pb.usbReqCount = 0;
  2723.             pPrinterPB->pb.usbFlags = kUSBIn;
  2724.             pPrinterPB->pb.usbClassType = kUSBBulk;
  2725.             
  2726.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2727.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2728.             err = USBFindNextPipe( &pPrinterPB->pb );
  2729.             if (immediateError(err))
  2730.             {
  2731.                 USBExpertFatalError(pPrinterPB->interfaceRef, kUSBInternalErr, "\p"kStrPrinterClass"kFindBulkInPipe - immediate error", err);
  2732.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2733.             }
  2734.             break;
  2735.             
  2736.         case kTaskTimeRequired:
  2737.             USBExpertStatus(pPrinterPB->interfaceRef, "\p" kStrPrinterClass"kTaskTimeRequired", 0);
  2738.              // to stress test usb bus, fallthrough to kGetCentronicsStatus 
  2739.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2740.             
  2741.             pPrinterPB->pb.usbBuffer = 0;
  2742.             pPrinterPB->pb.usbActCount = 0;
  2743.             pPrinterPB->pb.usbReqCount = kUSBNoDelay;
  2744.             pPrinterPB->pb.usbFlags = kUSBTaskTimeFlag;
  2745.             
  2746.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2747.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2748.             pPrinterPB->delayInProgress = true;
  2749.             err = USBDelay(&pPrinterPB->pb);
  2750.             if(immediateError(err))
  2751.             {
  2752.                 USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "kTaskTimeRequired - immediate error", 0);
  2753.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2754.             }
  2755.             break;
  2756.  
  2757.         case kGetCentronicsStatus:
  2758.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2759.  
  2760.             CentronicsStatus( &pPrinterPB->pb,  &pPrinterPB->centronics.b, pPrinterPB->interfaceNumber );
  2761.             
  2762.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2763.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2764.             err = USBDeviceRequest(&pPrinterPB->pb);
  2765.             if(immediateError(err))
  2766.             {
  2767.                 USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "kGetCentronicsStatus Immediate error", 0);
  2768.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2769.             }
  2770.             break;
  2771.             
  2772.         case kDelayGetCentronicsStatus:
  2773.             SetNullUSBParamBlock( pPrinterPB->interfaceRef, &pPrinterPB->pb );
  2774.  
  2775.             pPrinterPB->pb.usbBuffer = 0;
  2776.             pPrinterPB->pb.usbActCount = 0;
  2777.             pPrinterPB->pb.usbReqCount = kUSS720StatusMSDelay;
  2778.             
  2779.             pPrinterPB->pb.usbRefcon |= kTransactionPending;
  2780.             pPrinterPB->pb.usbCompletion = (USBCompletion)PrinterDeviceCompletionProc;
  2781.             pPrinterPB->delayInProgress = true;
  2782.             err = USBDelay(&pPrinterPB->pb);
  2783.             if(immediateError(err))
  2784.             {
  2785.                 USBExpertFatalError(pb->usbReference, err, "\p" kStrPrinterClass "kDelayGetCentronicsStatus - immediate error", 0);
  2786.                 pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2787.             }
  2788.             break;
  2789.             
  2790.         default:
  2791.             USBExpertFatalError(pPrinterPB->deviceRef, kUSBInternalErr, "\p" kStrPrinterClass "InitiateTransaction - unknown state", pPrinterPB->pb.usbRefcon);
  2792.             pPrinterPB->pb.usbRefcon |= kReturnFromDriver;
  2793.             break;
  2794.     }
  2795.     
  2796.     if (pPrinterPB->pb.usbRefcon & kReturnFromDriver)
  2797.     {
  2798.         pPrinterPB->pb.usbCompletion = (USBCompletion) NULL;
  2799.     }
  2800. }
  2801.  
  2802.  
  2803. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2804.     Name:        PrintDriverEntry
  2805.  
  2806.     Input Parameters:    
  2807.         
  2808.     Output Parameters:
  2809.         
  2810.     Description:
  2811.         This is where the system instantiates a USB printing device.
  2812.  
  2813.         We need to install drivers in the MacOS unitTable, and a reference
  2814.         in the name registry.
  2815.         
  2816.         But the information we need to do this is only available after some 
  2817.         USB transactions have completed. So we initiate here a series of asynchronous
  2818.         USB operations to get that information (by calling the first 
  2819.  
  2820.     Change History:
  2821.         31 Jul 1998,    oja:        page-aligned double buffer i/o
  2822.         30 Jun 1998,    oja:        change CentronicsStatus to ControlStatusRequests
  2823.         28 Feb 1998,    oja:        Original version.
  2824. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2825. void 
  2826. PrintDriverEntry(
  2827.     USBDeviceRef                    deviceRef,
  2828.     USBDeviceDescriptorPtr        pDeviceDesc,
  2829.     USBInterfaceDescriptorPtr    pInterfaceDesc,
  2830.     UInt32                            interfaceNumber
  2831.     )
  2832. {
  2833.     static Boolean        beenThereDoneThat = false;
  2834.     OSStatus                err;
  2835.     
  2836.     
  2837.     RoutineDescriptor qw = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBWriteProcInfo, QueueWrite);
  2838.     RoutineDescriptor qr = BUILD_ROUTINE_DESCRIPTOR( uppQueueUSBReadProcInfo, QueueRead);
  2839.     RoutineDescriptor qa = BUILD_ROUTINE_DESCRIPTOR( uppAbortProcInfo, Abort);
  2840.     RoutineDescriptor qs = BUILD_ROUTINE_DESCRIPTOR( uppControlStatusProcInfo, ControlStatusRequests );
  2841.     
  2842.     if( !beenThereDoneThat)
  2843.     {
  2844.         beenThereDoneThat = true;
  2845.         
  2846.         USBExpertStatus(deviceRef, "\p"kStrPrinterClass"Starting USB Printer Driver", 0);
  2847.         
  2848.         printerClassRecord.deviceDescriptor = *pDeviceDesc;    /* keep a copy of the device descriptor */
  2849.         printerClassRecord.pInterfaceDescriptor = pInterfaceDesc;
  2850.         printerClassRecord.interfaceNumber = interfaceNumber;
  2851.         
  2852.         printerClassRecord.deviceRef = deviceRef;
  2853.         printerClassRecord.interfaceRef = deviceRef;
  2854.         
  2855.         printerClassRecord.transDepth = 0;            /* init Delay Callback Depth */
  2856.     
  2857.         printerClassRecord.inRefNum =  -1;            /* initially no DRVRs added to UnitTable */
  2858.         printerClassRecord.outRefNum =  -1;    
  2859.         err = LoadResources( &printerClassRecord );
  2860.         if ( err != noErr )
  2861.             USBExpertFatalError( deviceRef, err, "\p" kStrPrinterClass "LoadResources failed", 0);
  2862.         //
  2863.         //    routines to write and read to the device must be called by 68K DRVR
  2864.         //        so we use mixed-mode manager to dispatch between PPC and 68K
  2865.         //
  2866.         printerClassRecord.qwrite = (QueueUSBWriteUPP) &printerClassRecord.qwriteRD;
  2867.         printerClassRecord.qwriteRD = qw;
  2868.     
  2869.         printerClassRecord.qread = (QueueUSBReadUPP) &printerClassRecord.qreadRD;
  2870.         printerClassRecord.qreadRD = qr;    
  2871.         
  2872.         printerClassRecord.qstatus = (ControlStatusUPP) &printerClassRecord.qstatusRD;
  2873.         printerClassRecord.qstatusRD = qs;
  2874.  
  2875.         printerClassRecord.qabort = (AbortUPP) &printerClassRecord.qabortRD;
  2876.         printerClassRecord.qabortRD = qa;
  2877.  
  2878.         printerClassRecord.r = (QueueUSBReadUPP) QueueRead;
  2879.         printerClassRecord.w = (QueueUSBWriteUPP) QueueWrite;
  2880.         printerClassRecord.s = (ControlStatusUPP) ControlStatusRequests;
  2881.         printerClassRecord.a = (AbortUPP) Abort;
  2882.  
  2883.         SetNullUSBParamBlock( deviceRef, &printerClassRecord.pb );
  2884.         SetNullUSBParamBlock( 0, &printerClassRecord.in );        // fill in pipe ref later
  2885.         SetNullUSBParamBlock( 0, &printerClassRecord.out );    // fill in pipe ref later
  2886.  
  2887. #if DOUBLE_BUFFER
  2888.         //
  2889.         // Assume 1. TRANSFER_SIZE is a power of 2
  2890.         //    Assume 2. malignedBuffer is allocated to be 3*TRANSFER_SIZE
  2891.         //
  2892.         printerClassRecord.pageWriteAlignedBufferSize = TRANSFER_SIZE;                            // should get this from VM
  2893.         printerClassRecord.pageWriteAlignedBuffer = printerClassRecord.malignedBuffer;
  2894.         // align it below the buffer, then bring it into the range of the buffer
  2895.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) &= ~(printerClassRecord.pageWriteAlignedBufferSize - 1);    //assumption1
  2896.         *((UInt32 *) &printerClassRecord.pageWriteAlignedBuffer) += printerClassRecord.pageWriteAlignedBufferSize;            //assumption2
  2897.  
  2898.         printerClassRecord.pageReadAlignedBufferSize = TRANSFER_SIZE;
  2899.         printerClassRecord.pageReadAlignedBuffer = printerClassRecord.pageWriteAlignedBuffer + TRANSFER_SIZE;
  2900. #endif
  2901.         printerClassRecord.terminating = false;
  2902.         printerClassRecord.printerConfigured = false;
  2903.     
  2904.         //
  2905.         //    Just to be thorough, lets hold our paramter blocks so that we won't page them at
  2906.         //        interrupt time. (We should be in the System heap and automatically held.)
  2907.         //
  2908.         HoldMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  2909.  
  2910.  
  2911.         //
  2912.         // Start out at first state
  2913.         //
  2914.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  2915.         printerClassRecord.pb.usbRefcon = kFindInterface_bidirectional;
  2916.         PrinterDeviceInitiateTransaction(&printerClassRecord.pb);
  2917.     }
  2918. }
  2919.  
  2920. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2921.     Name:        PrinterRemovalNotification
  2922.  
  2923.     Input Parameters:    
  2924.         
  2925.     Output Parameters:
  2926.         
  2927.     Description:
  2928.         release any allocated storage
  2929.         remove DRVRs from the UnitTable
  2930.  
  2931.         One small complication happens when the USS-720 cable is used. It's possible
  2932.         that the user has the device plugged in, but the printer wasn't powered on.
  2933.         In this case, our state machine is still cycling between the states 
  2934.         kDelayGetCapability and kGetCapabilityString. If we terminate before the delay
  2935.         returns we'll crash the system. We monitor terminating to handle this
  2936.         
  2937.     Change History:
  2938.         17 Aug 1998,    oja:        don't deregister if the root hub was hot unplugged
  2939.         10 Aug 1998,    oja:        call Abort to cleanup pending read/write transactions
  2940.         31 Jul 1998,    oja:        cleanup some hotplugging problems
  2941.         12 Jul 1998,    oja:        allow for hot unplugging during initial startup
  2942.                                             wait for completion if refCon indicates some
  2943.                                             transaction is in progress
  2944.         24 Apr 1998,    oja:        added call to DeregisterDevice
  2945.         28 Feb 1998,    oja:        Original version.
  2946. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  2947. OSStatus
  2948. PrinterRemovalNotification( void )
  2949. {
  2950. static    Boolean    logfileclosed = false;
  2951. static    Boolean    aborted = false;
  2952. static    Boolean    deregistered = false;
  2953. static    Boolean    readpipeaborted = false;
  2954. static    Boolean    writepipeaborted = false;
  2955. static    Boolean    timedout = false;
  2956. OSStatus            result = noErr;
  2957. static unsigned long    tc = 0;
  2958.     //
  2959.     //    notify state machine not to continue
  2960.     //
  2961.     printerClassRecord.terminating = true;
  2962.     
  2963.     USBExpertStatus( printerClassRecord.deviceRef, "\p"kStrPrinterClass"Driver removal notification received", 0);
  2964.     if (!logfileclosed)
  2965.     {
  2966.         LOGGING( fclose( logfile ) );
  2967.         logfileclosed = true;
  2968.         return (OSStatus) kUSBDeviceBusy;
  2969.     }
  2970.     
  2971.     // per the Mac OS USB DDK API Ref 
  2972.     // "If the device associated with this call [USBDelay] is unplugged and its driver removed while
  2973.     //  this function call is pending, the function will not complete."
  2974.     // therefore don't hang around if a delay is in progress
  2975.     if (( printerClassRecord.pb.usbCompletion != (USBCompletion) NULL ) && (!printerClassRecord.delayInProgress))
  2976.     {
  2977.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Waiting for configuration to complete", printerClassRecord.pb.usbRefcon);
  2978.         return (OSStatus) kUSBDeviceBusy;
  2979.     }
  2980.     
  2981.     // Abort any outstanding write requests
  2982.     if (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL ) && (!writepipeaborted))
  2983.     {
  2984.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Abort write pipe", printerClassRecord.writePipeRef);
  2985.         USBAbortPipeByReference( printerClassRecord.writePipeRef );
  2986.         writepipeaborted = true;
  2987.         return (OSStatus) kUSBDeviceBusy;
  2988.     }
  2989.     
  2990.     // Abort any outstanding read requests
  2991.     if (( printerClassRecord.in.usbCompletion != (USBCompletion) NULL ) && (!readpipeaborted))
  2992.     {
  2993.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Abort read pipe", printerClassRecord.readPipeRef );
  2994.         USBAbortPipeByReference( printerClassRecord.readPipeRef );
  2995.         readpipeaborted = true;
  2996.         return (OSStatus) kUSBDeviceBusy;
  2997.     }
  2998.     
  2999.     // Abort any outstanding transactions
  3000.     if (!aborted)
  3001.     {
  3002.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Call Abort()", 0);
  3003.         Abort( 0, &printerClassRecord );
  3004.         aborted = true;
  3005.         return (OSStatus) kUSBDeviceBusy;
  3006.     }
  3007.  
  3008.     // wait up to ten seconds for the read & write routines to complete.  When they do, the completion procptrs will be NULL'd
  3009.     if (tc == 0)
  3010.         tc = TickCount() + 10*60;
  3011.         
  3012.     if ( TickCount() >= tc )
  3013.         timedout = true;
  3014.         
  3015.     if (( TickCount() < tc ) &&
  3016.          (( printerClassRecord.out.usbCompletion != (USBCompletion) NULL) ||
  3017.           ( printerClassRecord.in.usbCompletion != (USBCompletion) NULL )))
  3018.     {
  3019.         return (OSStatus) kUSBDeviceBusy;
  3020.     }
  3021.     
  3022.     // Put the appropriate timeout message in the log
  3023.     if ( timedout )
  3024.     {
  3025.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"took longer than 10 seconds for read/write pipes to complete", 0);
  3026.     }
  3027.     else
  3028.     {
  3029.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Pipes closed normally", 0);
  3030.     }
  3031.     
  3032.     if (!deregistered)        
  3033.     {
  3034.         //
  3035.         //    remove printer from the name registry
  3036.         //
  3037.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Removed printer entry from nameregistry", 0);
  3038.         DeregisterDevice( &printerClassRecord );
  3039.         deregistered = true;
  3040.         return (OSStatus) kUSBDeviceBusy;
  3041.     }
  3042.  
  3043.     //
  3044.     //    release any allocated storage
  3045.     //
  3046.     if ( printerClassRecord.pCapabilityString != printerClassRecord.capability )
  3047.     {
  3048.         USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Deallocated capability string memory", 0);
  3049.         printerClassRecord.pb.usbReference = printerClassRecord.deviceRef;             
  3050.         printerClassRecord.pb.usbFlags = 0;             
  3051.         printerClassRecord.pb.usbRefcon = kDeallocateCapbilityString;             
  3052.         printerClassRecord.pb.usbBuffer = printerClassRecord.pCapabilityString;        
  3053.         printerClassRecord.pb.usbCompletion = (USBCompletion)kUSBNoCallBack;
  3054.         printerClassRecord.delayInProgress = true;        // this prevents the control pipe completion procptr from being checked
  3055.         USBDeallocMem(&printerClassRecord.pb);
  3056.         
  3057.         printerClassRecord.pCapabilityString = printerClassRecord.capability;
  3058.         return (OSStatus) kUSBDeviceBusy;
  3059.     }
  3060.  
  3061.     //
  3062.     //    don't need to hang on to param blocks after we've gone away
  3063.     //
  3064.     UnholdMemory( &printerClassRecord, sizeof(struct usbPrinterPBStruct) );
  3065.  
  3066.     USBExpertStatus(printerClassRecord.deviceRef, "\p"kStrPrinterClass"Ready for removal", 0);
  3067.     return kUSBNoErr;
  3068. }
  3069.  
  3070. /*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  3071.     Name:        CFMInitialization
  3072.  
  3073.     Input Parameters:    
  3074.         initBlock
  3075.         
  3076.     Output Parameters:
  3077.         printerClassDriverFileSpec        set global
  3078.         
  3079.     Description:
  3080.         We use the code fragment initialization to get our filespec which 
  3081.         LoadResources will use to open our resource fork.
  3082.         
  3083.         A peculiarity of the USB 1.0 implementation is that does not lock the
  3084.         driver into physical memory. As a result a driver which does not call
  3085.         SetDriverClosureMemory on it's fragment will likely be paged in during
  3086.         interrupt time and a double bus-fault will occur. The solution for this
  3087.         is to have the USB Expert call SetDriverClosureMemory in a future release
  3088.         of the USB stack. In the meantime, we call it on ourselves to lock us into
  3089.         physical memory. When the USB stack is revved, one call to SetDriverClosureMemory
  3090.         (either this one or the Expert's) will be treated as a NOP.
  3091.  
  3092.     Change History:
  3093.         31 Jul 1998,    oja:        added call to SetDriverClosureMemory
  3094.         11 Jun 1998,    oja:        Original version.
  3095. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
  3096. OSErr
  3097. CFMInitialization( CFragInitBlock *initBlock )
  3098. {
  3099.     //
  3100.     //    get a reference to our file so that we can open up the resource fork later on
  3101.     //
  3102.     if ( CFragHasFileLocation( initBlock->fragLocator.where ) )
  3103.         printerClassDriverFileSpec = *(initBlock->fragLocator.u.onDisk.fileSpec);
  3104.  
  3105.     // don't page us, we're a device driver
  3106.     return SetDriverClosureMemory( (CFragConnectionID) initBlock->closureID, true );
  3107.  
  3108. }
  3109.  
  3110. // eof
  3111.